Shell Scripting – The IF statement
The most common type of decision construct in shell scripting is the IF statement.
Some Rules
Here are some common rules that govern the IF construct:
- elif – (Else IF) else statements are optional
- You can have an unlimited number of elif statements
- The “do these commands” statements can consist of multiple commands – one per line
- The end of the statement is a backwards IF (fi)
- Commands run true if they function properly
Let’s see it in our shell script that we have been building.
Notice that the [ ANSWER = “y” ] is used as a test. This is called a string comparison.
It is important to note that there are spaces before and after the square brackets for out test. If you do not have the spaces you will get an error message.
When we type in “y” for yes, we get the listing for the directory (ls -F).
Common test statements
Test Statement | Returns True if |
[ A = B ] | String A is equal to String B |
[ A != B ] | String A is not equal to string B |
[ A -eq B ] | A is numerically equal to B |
[ A -ne B ] | A is not numerically equal to B |
[ A -lt B ] | A is numerically less than B |
[ A -gt B ] | A is numerically greater than B |
[ A -le B ] | A is numerically less than or equal to B |
[ A -ge B ] | A is numerically greater than or equal to B |
[ -r A ] | A is a file/directory that exists and is readable (r permission) |
[ -w A ] | A is a file/directory that exists and is writable (w permission) |
[ -x A ] | A is a file/directory that exists and is executable (x permission) |
[ -f A ] | A is a file that exists |
[ -d A ] | A is a directory that exists |
Here is the code that we have been working on all zipped up and ready for you to take a look at.