Let’s make our bash scripts clever!
On this a part of the bash newbie collection, you’ll discover ways to use conditional statements in your bash scripts to make it behave in a different way in numerous eventualities and circumstances.
This manner you’ll be able to construct way more environment friendly bash scripts and you may also implement error checking in your scripts.
Utilizing if assertion in bash
Essentially the most elementary assemble in any decision-making construction is an if situation. The final syntax of a primary if assertion is as follows:
if [ condition ]; then
your code
fi
The if assertion is closed with a fi (reverse of if).
Take note of white house!
- There have to be an area between the opening and shutting brackets and the situation you write. In any other case, the shell will complain of error.
- There have to be house earlier than and after the conditional operator (=, ==, <= and many others). In any other case, you will see an error like “unary operator anticipated”.
Now, let’s create an instance script root.sh. This script will echo the assertion “you’re root” provided that you run the script as the foundation consumer:
#!/bin/bash
if [ $(whoami) = ‘root’ ]; then
echo “You’re root”
fi
The whoami command outputs the username. From the bash variables tutorial, you already know that $(command) syntax is used for command substitution and it offers you the output of the command.
The situation $(whoami) = ‘root’ will probably be true solely in case you are logged in as the foundation consumer.
Do not imagine me? You do not have to. Run it and see it for your self.
Utilizing if-else assertion in bash
You’ll have observed that you simply don’t get any output whenever you run the foundation.sh script as an everyday consumer. Any code you need to run when an if situation is evaluated to false could be included in an else assertion as follows:
#!/bin/bash
if [ $(whoami) = ‘root’ ]; then
echo “You’re root”
else
echo “You aren’t root”
fi
Now whenever you run the script as an everyday consumer, you can be reminded that you’re not the almighty root consumer:
[email protected]:~$ ./root.sh
You aren’t root
Utilizing else if assertion in bash
You should use an elif (else-if) assertion everytime you need to take a look at a couple of expression (situation) on the identical time.
For instance, the next age.sh bash script takes your age as an argument and can output a significant message that corresponds to your age:
#!/bin/bash
AGE=$1
if [ $AGE -lt 13 ]; then
echo “You’re a child.”
elif [ $AGE -lt 20 ]; then
echo “You’re a teenager.”
elif [ $AGE -lt 65 ]; then
echo “You’re an grownup.”
else
echo “You’re an elder.”
fi
Now do a couple of runs of the age.sh script to check out with totally different ages:
[email protected]:~$ ./age.sh 11
You’re a child.
[email protected]:~$ ./age.sh 18
You’re a teenager.
[email protected]:~$ ./age.sh 44
You’re an grownup.
[email protected]:~$ ./age.sh 70
You’re an elder.
Discover that I’ve used the -lt (lower than) take a look at situation with the $AGE variable.
Additionally bear in mind you could have a number of elif statements however just one else assertion in an if assemble and it have to be closed with a fi.
Utilizing nested if statements in bash
You can too use an if assertion inside one other if assertion. For instance, check out the next climate.sh bash script:
#!/bin/bash
TEMP=$1
if [ $TEMP -gt 5 ]; then
if [ $TEMP -lt 15 ]; then
echo “The climate is chilly.”
elif [ $TEMP -lt 25 ]; then
echo “The climate is good.”
else
echo “The climate is sizzling.”
fi
else
echo “It is freezing outdoors …”
fi
The script takes any temperature as an argument after which shows a message that displays what would the climate be like. If the temperature is larger than 5, then the nested (interior) if-elif assertion is evaluated. Let’s do a couple of runs of the script to see the way it works:
[email protected]:~$ ./climate.sh 0
It is freezing outdoors …
[email protected]:~$ ./climate.sh 8
The climate is chilly.
[email protected]:~$ ./climate.sh 16
The climate is good.
[email protected]:~$ ./climate.sh 30
The climate is sizzling.
Utilizing Case assertion in bash
You can too use case statements in bash to switch a number of if statements as they’re generally complicated and exhausting to learn. The final syntax of a case assemble is as follows:
case “variable” in
“pattern1” )
Command … ;;
“pattern2” )
Command … ;;
“pattern2” )
Command … ;;
esac
Concentrate!
- The patterns are all the time adopted by a clean house and ).
- Instructions are all the time adopted by double semicolon ;;. White house just isn’t obligatory earlier than it.
- Case statements finish with esac (reverse of case).
Case statements are notably helpful when coping with sample matching or common expressions. To display, check out the next char.sh bash script:
#!/bin/bash
CHAR=$1
case $CHAR in
[a-z])
echo “Small Alphabet.” ;;
[A-Z])
echo “Large Alphabet.” ;;
[0-9])
echo “Quantity.” ;;
*)
echo “Particular Character.”
esac
The script takes one character as an argument and shows whether or not the character is small/huge alphabet, quantity, or a particular character.
[email protected]:~$ ./char.sh a
Small Alphabet.
[email protected]:~$ ./char.sh Z
Large Alphabet.
[email protected]:~$ ./char.sh 7
Quantity.
[email protected]:~$ ./char.sh $
Particular Character.
Discover that I’ve used the wildcard asterisk image
Take a look at situations in bash
There are quite a few take a look at situations that you need to use with if statements. Take a look at situations varies in case you are working with numbers, strings, or information. Consider them as logical operators in bash.
I’ve included a few of the hottest take a look at situations within the desk beneath:
Situation | Equal |
---|---|
$a -lt $b | $a < $b |
$a -gt $b | $a > $b |
$a -le $b | $a <= $b |
$a -ge $b | $a >= $b |
$a -eq $b | $a is the same as $b |
$a -ne $b | $a just isn’t equal to $b |
-e $FILE | $FILE exists |
-d $FILE | $FILE exists and is a listing. |
-f $FILE | $FILE exists and is an everyday file. |
-L $FILE | $FILE exists and is a gentle hyperlink. |
$STRING1 = $STRING2 | $STRING1 is the same as $STRING2 |
$STRING1 != $STRING2 | $STRING1 just isn’t equal to $STRING2 |
-z $STRING1 | $STRING1 is empty |
Fortunately, you don’t must memorize any of the take a look at situations as a result of you’ll be able to look them up within the take a look at man web page:
[email protected]:~$ man take a look at
Let’s create one closing script named filetype.sh that detects whether or not a file is an everyday file, listing or a gentle hyperlink:
#!/bin/bash
if [ $# -ne 1 ]; then
echo “Error: Invalid variety of arguments”
exit 1
fi
file=$1
if [ -f $file ]; then
echo “$file is an everyday file.”
elif [ -L $file ]; then
echo “$file is a gentle hyperlink.”
elif [ -d $file ]; then
echo “$file is a listing.”
else
echo “$file doesn’t exist”
fi
I improved the script just a little by including a verify on variety of arguments. If there are not any arguments or a couple of argument, the script will output a message and exit with out working remainder of the statements within the script.
Let’s do a couple of runs of the script to check it with numerous sorts of information:
[email protected]:~$ ./filetype.sh climate.sh
climate.sh is an everyday file.
[email protected]:~$ ./filetype.sh /bin
/bin is a gentle hyperlink.
[email protected]:~$ ./filetype.sh /var
/var is a listing.
[email protected]:~$ ./filetype.sh
Error: Invalid variety of arguments
Bonus: Bash if else assertion in a single line
To date all of the if else assertion you noticed have been utilized in a correct bash script. That is the respectable means of doing it however you aren’t obliged to it.
While you simply need to see the end result within the shell itself, you might use the if else statements in a single line in bash.
Suppose you’ve gotten this bash script.
if [ $(whoami) = ‘root’ ]; then
echo “You’re root”
else
echo “You aren’t root”
fi
You should use all of the if else statements in a single line like this:
if [ $(whoami) = ‘root’ ]; then echo “root”; else echo “not root”; fi
You may copy and paste the above in terminal and see the end result for your self.
Principally, you simply add semicolons after the instructions after which add the subsequent if-else assertion.
Superior! This could provide you with a superb understanding of conditional statements in Bash. I hope you’ve gotten loved making your bash scripts smarter!
Keep tuned for subsequent week as you’ll discover ways to use numerous loop constructs in your bash scripts.
multiple if condition in shell script example,bash if multiple conditions,bash script if else,bash if string equals,bash if else one line,bash if,if "-f" unix,bash if true