Skip to content
Home » [NEW] Bash Scripting Tutorial | if clause – NATAVIGUIDES

[NEW] Bash Scripting Tutorial | if clause – NATAVIGUIDES

if clause: คุณกำลังดูกระทู้

If Statements!

Decisions, decisions.

Introduction

Bash if statements are very useful. In this section of our Bash Scripting Tutorial you will learn the ways you may use if statements in your Bash scripts to help automate tasks.

If statements (and, closely related, case statements) allow us to make decisions in our Bash scripts. They allow us to decide whether or not to run a piece of code based upon conditions that we may set. If statements, combined with loops (which we’ll look at in the next section) allow us to make much more complex scripts which may solve larger tasks.

Like what we have looked at in previous sections, their syntax is very specific so stay on top of all the little details.

Basic If Statements

A basic if statement effectively says, if a particular test is true, then perform a given set of actions. If it is not true then don’t perform those actions. If follows the format below:

if [ <some test> ]
then
<commands>
fi

Anything between then and fi (if backwards) will be executed only if the test (between the square brackets) is true.

Let’s look at a simple example:

if_example.sh

  1. #!/bin/bash
  2. if [ $1 -gt 100 ]
  3. then
  4. echo Hey that\’s a large number.

  5. pwd

  6. fi
  7. date

Let’s break it down:

  • Line 4 – Let’s see if the first command line argument is greater than 100
  • Line 6 and 7 – Will only get run if the test on line 4 returns true. You can have as many commands here as you like.
  • Line 6 – The backslash ( \ ) in front of the single quote ( ‘ ) is needed as the single quote has a special meaning for bash and we don’t want that special meaning. The backslash escapes the special meaning to make it a normal plain single quote again.
  • Line 8 – fi signals the end of the if statement. All commands after this will be run as normal.
  • Line 10 – Because this command is outside the if statement it will be run regardless of the outcome of the if statement.
  1. ./if_example.sh 15

  2. Sun 14 Nov 6:37:13 2021
  3. ./if_example.sh 150

  4. Hey that’s a large number.
  5. /home/ryan/bin
  6. Sun 14 Nov 6:37:13 2021

It is always good practice to test your scripts with input that covers the different scenarios that are possible.

Test

The square brackets ( [ ] ) in the if statement above are actually a reference to the command test. This means that all of the operators that test allows may be used here as well. Look up the man page for test to see all of the possible operators (there are quite a few) but some of the more common ones are listed below.

Operator
Description

! EXPRESSION
The EXPRESSION is false.

-n STRING
The length of STRING is greater than zero.

-z STRING
The lengh of STRING is zero (ie it is empty).

STRING1 = STRING2
STRING1 is equal to STRING2

STRING1 != STRING2
STRING1 is not equal to STRING2

INTEGER1 -eq INTEGER2
INTEGER1 is numerically equal to INTEGER2

INTEGER1 -gt INTEGER2
INTEGER1 is numerically greater than INTEGER2

INTEGER1 -lt INTEGER2
INTEGER1 is numerically less than INTEGER2

-d FILE
FILE exists and is a directory.

-e FILE
FILE exists.

-r FILE
FILE exists and the read permission is granted.

-s FILE
FILE exists and it’s size is greater than zero (ie. it is not empty).

-w FILE
FILE exists and the write permission is granted.

-x FILE
FILE exists and the execute permission is granted.

A few points to note:

  • = is slightly different to -eq. [ 001 = 1 ] will return false as = does a string comparison (ie. character for character the same) whereas -eq does a numerical comparison meaning [ 001 -eq 1 ] will return true.
  • When we refer to FILE above we are actually meaning a path. Remember that a path may be absolute or relative and may refer to a file or a directory.
  • Because [ ] is just a reference to the command test we may experiment and trouble shoot with test on the command line to make sure our understanding of its behaviour is correct.
  1. test 001 = 1

  2. echo $?

  3. 1
  4. test 001 -eq 1

  5. echo $?

  6. 0
  7. touch myfile

  8. test -s myfile

  9. echo $?

  10. 1
  11. ls /etc > myfile

  12. test -s myfile

  13. echo $?

  14. 0

Let’s break it down:

  • Line 1 – Perform a string based comparison. Test doesn’t print the result so instead we check it’s exit status which is what we will do on the next line.
  • Line 2 – The variable $? holds the exit status of the previously run command (in this case test). 0 means TRUE (or success). 1 = FALSE (or failure).
  • Line 4 – This time we are performing a numerical comparison.
  • Line 7 – Create a new blank file myfile (assuming that myfile doesn’t already exist).
  • Line 8 – Is the size of myfile greater than zero?
  • Line 11Redirect some content into myfile so it’s size is greater than zero.
  • Line 12 – Test the size of myfile again. This time it is TRUE.

Indenting

You’ll notice that in the if statement above we indented the commands that were run if the statement was true. This is referred to as indenting and is an important part of writing good, clean code (in any language, not just Bash scripts). The aim is to improve readability and make it harder for us to make simple, silly mistakes. There aren’t any rules regarding indenting in Bash so you may indent or not indent however you like and your scripts will still run exactly the same. I would highly recommend you do indent your code however (especially as your scripts get larger) otherwise you will find it increasingly difficult to see the structure in your scripts.

Nested If statements

Talking of indenting. Here’s a perfect example of when it makes life easier for you. You may have as many if statements as necessary inside your script. It is also possible to have an if statement inside of another if statement. For example, we may want to analyse a number given on the command line like so:

nested_if.sh

  1. #!/bin/bash
  2. if [ $1 -gt 100 ]
  3. then
  4. echo Hey that\’s a large number.

  5. if (( $1 % 2 == 0 ))

  6. then

  7. echo And is also an even number.

  8. fi

  9. fi

Let’s break it down:

  • Line 4 – Perform the following, only if the first command line argument is greater than 100.
  • Line 8 – This is a light variation on the if statement. If we would like to check an expression then we may use the double brackets just like we did for variables.
  • Line 10 – Only gets run if both if statements are true.

Yo dawg, I herd you like if statements so I put an if statement inside your if statement.

Xzibit

(Xzibit didn’t actually say that but I’m sure he would have, had he hosted Pimp My Bash Script.)

You can nest as many if statements as you like but as a general rule of thumb if you need to nest more than 3 levels deep you should probably have a think about reorganising your logic.

If Else

Sometimes we want to perform a certain set of actions if a statement is true, and another set of actions if it is false. We can accommodate this with the else mechanism.

if [ <some test> ]
then
<commands>
else
<other commands>
fi

Now we could easily read from a file if it is supplied as a command line argument, else read from STDIN.

else.sh

  1. #!/bin/bash
  2. if [ $# -eq 1 ]
  3. then
  4. nl $1

  5. else
  6. nl /dev/stdin

  7. fi

If Elif Else

Sometimes we may have a series of conditions that may lead to different paths.

if [ <some test> ]
then
<commands>
elif [ <some test> ]
then
<different commands>
else
<other commands>
fi

For example it may be the case that if you are 18 or over you may go to the party. If you aren’t but you have a letter from your parents you may go but must be back before midnight. Otherwise you cannot go.

if_elif.sh

  1. #!/bin/bash
  2. if [ $1 -ge 18 ]
  3. then
  4. echo You may go to the party.

  5. elif [ $2 == ‘yes’ ]
  6. then
  7. echo You may go to the party but be back before midnight.

  8. else
  9. echo You may not go to the party.

  10. fi

You can have as many elif branches as you like. The final else is also optional.

Boolean Operations

Sometimes we only want to do something if multiple conditions are met. Other times we would like to perform the action if one of several condition is met. We can accommodate these with boolean operators.

  • and – &&
  • or – ||

For instance maybe we only want to perform an operation if the file is readable and has a size greater than zero.

and.sh

  1. #!/bin/bash
  2. if [ -r $1 ] && [ -s $1 ]
  3. then
  4. echo This file is useful.

  5. fi

Maybe we would like to perform something slightly different if the user is either bob or andy.

or.sh

  1. #!/bin/bash
  2. if [ $USER == ‘bob’ ] || [ $USER == ‘andy’ ]
  3. then
  4. ls -alh

  5. else
  6. ls

  7. fi

Case Statements

Sometimes we may wish to take different paths based upon a variable matching a series of patterns. We could use a series of if and elif statements but that would soon grow to be unweildly. Fortunately there is a case statement which can make things cleaner. It’s a little hard to explain so here are some examples to illustrate:

case <variable> in
<pattern 1>)
<commands>
;;
<pattern 2>)
<other commands>
;;
esac

Here is a basic example:

case.sh

  1. #!/bin/bash
  2. case $1 in
  3. start)

  4. echo starting

  5. ;;

  6. stop)

  7. echo stoping

  8. ;;

  9. restart)

  10. echo restarting

  11. ;;

  12. *)

  13. echo don\’t know

  14. ;;

  15. esac

Let’s break it down:

  • Line 4 – This line begins the casemechanism.
  • Line 5 – If $1 is equal to ‘start’ then perform the subsequent actions. the ) signifies the end of the pattern.
  • Line 7 – We identify the end of this set of statements with a double semi-colon ( ;; ). Following this is the next case to consider.
  • Line 14 – Remember that the test for each case is a pattern. The * represents any number of any character. It is essentialy a catch all if for if none of the other cases match. It is not necessary but is often used.
  • Line 17 – esac is case backwards and indicates we are at the end of the case statement. Any other statements after this will be executed normally.
  1. ./case.sh start

  2. starting
  3. ./case.sh restart

  4. restarting
  5. ./case.sh blah

  6. don’t know

Now let’s look at a slightly more complex example where patterns are used a bit more.

disk_useage.sh

  1. #!/bin/bash
  2. space_free=$( df -h | awk ‘{ print $5 }’ | sort -n | tail -n 1 | sed ‘s/%//’ )
  3. case $space_free in
  4. [1-5]*)

  5. echo Plenty of disk space available

  6. ;;

  7. [6-7]*)

  8. echo There could be a problem in the near future

  9. ;;

  10. 8*)

  11. echo Maybe we should look at clearing out old files

  12. ;;

  13. 9*)

  14. echo We could have a serious problem on our hands soon

  15. ;;

  16. *)

  17. echo Something is not quite right here

  18. ;;

  19. esac

Summary

if
Perform a set of commands if a test is true.
else
If the test is not true then perform a different set of commands.
elif
If the previous test returned false then try this one.
&&
Perform the and operation.
||
Perform the or operation.
case
Choose a set of commands to execute depending on a string matching a particular pattern.
Indenting
Indenting makes your code much easier to read. It get’s increasingly important as your Bash scripts get longer.
Planning
Now that your scripts are getting a little more complex you will probably want to spend a little bit of time thinking about how you structure them before diving in.

Activities

Now let’s make some decisions.

  • Create a Bash script which will take 2 numbers as command line arguments. It will print to the screen the larger of the two numbers.
  • Create a Bash script which will accept a file as a command line argument and analyse it in certain ways. eg. you could check if the file is executable or writable. You should print a certain message if true and another if false.
  • Create a Bash script which will print a message based upon which day of the week it is (eg. ‘Happy hump day’ for Wedensday, ‘TGIF’ for Friday etc).

[Update] Future Conditional Forms | if clause – NATAVIGUIDES

Future Conditionals

Future Real Conditional

FORM

[If / When … simple present …, … simple future …]

[… simple future … if / when … simple present …]

Notice that there is no future in the if- or when-clause.

USE

The future real conditional (also called conditional 1) describes what you think you will do in a specific situation in the future. It is different from other real conditional forms because, unlike the present or the past, you do not know what will happen in the future. Although this form is called “real”, you are usually imagining or guessing about the future. It is called “real” because it is still possible that the action might occur in the future. Carefully study the following examples and compare them to the future unreal conditional examples further down the page.

Examples:

  • If I go to my friend’s house for dinner tonight, I will take a bottle of wine or some flowers.
    I am still not sure if I will go to his house or not.
  • When I have a day off from work, I am going to go to the beach.
    I have to wait until I have a day off.
  • If the weather is nice, she is going to walk to work.
    It depends on the weather.
  • Jerry will help me with my homework when he has time.
    I have to wait until he has time.
  • I am going to read if there is nothing on TV.
    It depends on the TV schedule.
  • A: What are you going to do if it rains?
    B: I am going to stay at home.

IMPORTANT If / When

Both “if” and “when” are used in the future real conditional, but the use is different from other real conditional forms. In the future real conditional, “if” suggests that you do not know if something will happen or not. “When” suggests that something will definitely happen at some point; we are simply waiting for it to occur. Notice also that the Simple Future is not used in if-clauses or when-clauses.

Examples:

  • When you call me, I will give you the address.
    You are going to call me later, and at that time, I will give you the address.
  • If you call me, I will give you the address.
    If you want the address, you can call me.

Future Unreal Conditional

FORM 1 (Most Common Form)

[If … simple past …, … would + verb …]

[… would + verb … if … simple past …]

Notice that this form looks the same as Present Unreal Conditional.

USE

The future unreal conditional is used to talk about imaginary situations in the future. It is not as common as the future real conditional because English speakers often leave open the possibility that anything MIGHT happen in the future. It is only used when a speaker needs to emphasize that something is impossible. Because this form looks like Present Unreal Conditional, many native speakers prefer Form 2 described below.

Examples:

  • If I had a day off from work next week, I would go to the beach.
    I don’t have a day off from work.
  • I am busy next week. If I had time, I would come to your party.
    I can’t come.
  • Jerry would help me with my homework tomorrow if he didn’t have to work.
    He does have to work tomorrow.

FORM 2

[If … were + present participle …, … would be + present participle …]

[… would be + present participle … if … were + present participle …]

USE

Form 2 of the future unreal conditional is also used to talk about imaginary situations in the future. Native speakers often prefer this form over Form 1 to emphasize that the conditional form is in the future rather than the present. Also notice in the examples below that this form can be used in the if-clause, the result, or both parts of the sentence.

Examples:

  • If I were going to Fiji next week, I would be taking my scuba diving gear with me. In if-clause and result
    I am not going to go to Fiji and I am not going to take my scuba gear with me.
  • If I were not visiting my grandmother tomorrow, I would help you study. In if-clause
    I am going to visit my grandmother tomorrow.
  • I am busy next week. If I had time, I would be coming to your party. In result
    I am not going to come to your party.

FORM 3

[If … were going to + verb …, … would be + present participle …]

[… would be + present participle … if … were going to + verb …]

USE

Form 3 of the future unreal conditional is a variation of Form 2 which is also used to talk about imaginary situations in the future. Notice that this form is only different from Form 2 in the if-clause. Native speakers use Form 3 to emphasize that the conditional form is a plan or prediction in the same way “be going to” is used to indicate a plan or prediction.

Examples:

  • If I were going to go to Fiji next week, I would be taking my scuba diving gear with me.
    I am not going to go to Fiji and I am not going to take my scuba gear with me.
  • If I were not going to visit my grandmother tomorrow, I would help you study.
    I am going to visit my grandmother tomorrow.

IMPORTANT Only use “If”

Only the word “if” is used with the past unreal conditional because you are discussing imaginary situations. “When” cannot be used.

Examples:

  • I would buy that computer tomorrow when it were cheaper. Not Correct
  • I would buy that computer tomorrow if it were cheaper. Correct

EXCEPTION Conditional with Modal Verbs

There are some special conditional forms for modal verbs in English:

would + can = could

would + shall = should

would + may = might

The words “can,” “shall” and “may” cannot be used with “would.” Instead, they must be used in these special forms.

Examples:

  • If I went to Egypt next year, I would can learn Arabic. Unfortunately, that’s not possible. Not Correct
  • If I went to Egypt next year, I could learn Arabic. Unfortunately, that’s not possible. Correct

The words “could,” should,” “might” and “ought to” include conditional, so you cannot combine them with “would.”

Examples:

  • If I didn’t have to work tonight, I would could go to the fitness center. Not Correct
  • If I didn’t have to work tonight, I could go to the fitness center. Correct

Future Real Conditional vs. Future Unreal Conditional

To help you understand the difference between the future real conditional and the future unreal conditional, compare the examples below:

Examples:

  • If you help me move tomorrow, I will buy you dinner. Future Real Conditional
    I don’t know if you can help me.
  • If you helped me move tomorrow, I would buy you dinner. Future Unreal Conditional
    You can’t help me, or you don’t want to help me.

Future Conditional Exercises

Conditional Exercise 7Future Real Conditional
Conditional Exercise 8Future Real Conditional vs. Future Unreal Conditional


Mixed Verb Tenses in English: Conditionals and IF clauses


How many verb tenses can you count in the following sentences? \”If you practice every day, you will improve. But you also need to know that if you didn’t develop good study habits in the past, you might have trouble in the future.\” There are several verb tenses in this excerpt, and they are all mixed together. But complex sentences like these are what make English a very rich and interesting language. In this challenging lesson, we will look at conditional sentences that mix tenses and even use the verb \”will\” in the \”if\” clause. Make sure to do the quiz at http://www.engvid.com/mixedverbtensesinenglishconditionalsandifclauses/ to practice and perfect your understanding of mixed tenses.
TRANSCRIPT
Hi again. Welcome to www.engvid.com. I’m Adam. Today’s lesson is a little bit tricky. It’s grammar, it’s conditionals, but we’re going to look at \”Mixed Conditionals\”. Now, before I get into the different types of ways that you can mix tenses and the conditionals, I want to do a very quick review of the conditionals that most of you learn in your ESL classes or your English… Other English classes, because these are the ones that are most commonly taught, and everybody, all your teachers want you to memorize these structures. The problem is then you might see mixed conditionals in other places, and you get all confused. Okay? I’m not going to get too deep into these, because you can find other good lessons by other engVid teachers who have already covered some of these on the site. I’m just going to do a quick review, and then I’ll get into… Deeper into the mixed conditionals.
So here are the four main types of conditionals you learn: \”If I won the lottery, I’d buy a house.\” So this, just so we are clear, is \”would\”, I’ve contracted it to \”I’d\”. \”If I won\”, I have simple past tense, plus \”would\” in the second clause, in the condition clause, in the result clause. \”If I had known she was coming, I’d have come too.\” Okay? Here I have the past perfect, plus \”would have\” plus PP, past participle verb. Now, these are both unreal, mean… Meaning that they are hypothetical, they are imaginary. This is about a future or present unreal situation. I didn’t win the lottery, I’m not buying a house; this is all just imagination. This is about the past. Now, the reason it is unreal is because I can’t go and change the past. So, this didn’t happen, and so this didn’t happen. This is, again, imagination, but we’re looking at the past. Okay?
\”If you boil water, it evaporates.\” If you notice here, I have simple present verb and simple present verb. This is a real conditional. It means it’s true. Whenever you have a factokay?a result is based on this condition and it’s always true… By the way, \”evaporates\” means becomes steam, it goes away. Right? If you boil water, eventually you have no more water in the pot. So this is a real conditional, always true. Simple present, simple present. Lastly: \”If you study hard, you will pass the test.\” Simple present verb, \”will\”, verb, like future. So, again, this is a real situation, because this is true. If you do this, this will happen as a result. So these are the ones that you mostly learn.
If you have any questions, again, go to www.engvid.com, find the lessons about these that can explain it in more detail. But now we’re going to see other situations, other sentences with \”if\” conditionals that are not like these. Sometimes we can mix tenses, sometimes you can… Sorry. Let me stop myself, here. Sometimes your teachers tell you: \”Never put ‘will’ with the ‘if’ clause.\” Well, what I’m going to show you is that sometimes, yeah, you can. This is the problem with English: There’s always exceptions to the rules. Today we’re going to look at some of those exceptions. Okay? Let’s see what happens.
Okay. So now we’re going to look at a few different types of mixtures, if you want to call it that, with the \”if\” clauses. But before I start to show you these examples, I want you to understand that these mixed conditionals are all about context. You can generally understand what is going on, what the relationship between the two verbs are by looking at the context, looking at the time, looking at the place, looking at the situation that’s going on, and should… It usually should be very clear, but in case you’re wondering how to construct these so you can use them yourselves, I’ll show you with a few examples. Okay? These are in no particular order. They’re just examples, and we’re going to look at them individually.

นอกจากการดูบทความนี้แล้ว คุณยังสามารถดูข้อมูลที่เป็นประโยชน์อื่นๆ อีกมากมายที่เราให้ไว้ที่นี่: ดูความรู้เพิ่มเติมที่นี่

Mixed Verb Tenses in English: Conditionals and IF clauses

ติว TOEIC : วิธีจำโครงสร้าง If-Clause 3 แบบ ให้แม่น!


✿ ติวสอบ TOEIC® เริ่มจากพื้นฐาน เทคนิคแกรมม่า แนวข้อสอบ TOEIC® ล่าสุด! ✿
👉 ทดลองติวฟรี! ➡️ https://bit.ly/2wR4Gmu
✿ คอร์สครูดิว ติวสอบ TOEIC® มีอะไรให้บ้าง? ✿
✅ติวเทคนิคสอบ TOEIC® รวม Grammar ที่ใช้สอบ ครบถ้วน สอนจากพื้นฐาน เรียนได้ทุกคนแน่นอน
✅เก็งศัพท์สอบ TOEIC® ออกข้อสอบบ่อย ๆ ให้ครบ ไม่ต้องเสียเวลาไปนั่งรวบรวมเอง
✅ ติวข้อสอบ TOEIC® ล่าสุด ทั้ง Reading และ Listening
✅สามารถสอบถามข้อหรือจุดที่สงสัยได้ตลอด
✅การันตี 750+ (ถ้าสอบแล้วไม่ถึง สามารถทวนคอร์สได้ฟรี)
📣 ถ้าไม่อยากพลาดคลิปดีๆแบบนี้ อย่าลืมกด ❤️ Subscribe ❤️กันนะคะ

ติว TOEIC : วิธีจำโครงสร้าง If-Clause 3 แบบ ให้แม่น!

BAHASA INGGRIS Kelas 12 – If Clause \u0026 If Conditional | GIA Academy


Hai temanteman,
Belajar membuat kalimat pengandaian bareng Teacher Ayu, yukk!
Narator : Siti Ayu Permatasari

bahasainggriskelas12
ifclause
ifconditional
semestersatu
videobelajar
belajarjarakjauh
ifclausekelas12

BAHASA INGGRIS Kelas 12 - If Clause \u0026 If Conditional | GIA Academy

Conditional and IF clauses – Learn English Grammar


Do you know how to use English conditional and IF clauses? Click here https://goo.gl/9eEuH3 and get your TOEIC strategies guide to have a great result at this English exam! ↓ Check How Below ↓
Step 1: Go to https://goo.gl/9eEuH3
Step 2: Sign up for a Free Lifetime Account No money, No credit card required
Step 3: Learn with the best online resources and quickly become conversational.
In this English grammar lesson you will learn everything you need about conditional and if clauses of the English language. With this video you will be able to able to improve your English grammar. Are you ready to avoid doing common English mistakes?
Our English host gives you easy to understand explanations. This is THE FASTEST way to easily take your English ability to the next level!
■ Facebook: https://www.facebook.com/EnglishClass101
■ Twitter: https://twitter.com/EnglishClass101
Click here to get started with English: https://goo.gl/9eEuH3
Also, please LIKE, SHARE and COMMENT on our videos! We really appreciate it. Thanks!

Conditional and IF clauses - Learn English Grammar

Learn English Grammar: The 4 Conditionals


Do conditionals in English drive you crazy? They’re so easy to get mixed up! There are four conditionals in English grammar, numbered zero through three. So in this lesson I’ll give you an overview of all four, with examples of each. If you watch this video and do the quiz at https://www.engvid.com/learnenglishgrammarthe4conditionals/ you will have a better understanding of conditionals in English. (That last sentence is an example of the first conditional!)

Learn English Grammar: The 4 Conditionals

นอกจากการดูบทความนี้แล้ว คุณยังสามารถดูข้อมูลที่เป็นประโยชน์อื่นๆ อีกมากมายที่เราให้ไว้ที่นี่: ดูบทความเพิ่มเติมในหมวดหมู่LEARN FOREIGN LANGUAGE

ขอบคุณที่รับชมกระทู้ครับ if clause

Leave a Reply

Your email address will not be published. Required fields are marked *