Shell Scripting – The IF statement

Shell Scripting – The IF statement

The most common type of decision construct in shell scripting is the IF statement.

IF Statement

Some Rules

Here are some common rules that govern the IF construct:

  1. elif – (Else IF) else statements are optional
  2. You can have an unlimited number of elif statements
  3. The “do these commands” statements can consist of multiple commands – one per line
  4. The end of the statement is a backwards IF (fi)
  5. Commands run true if they function properly

Let’s see it in our shell script that we have been building.

directory information y/n

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.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 3

No votes so far! Be the first to rate this post.



Updated on October 29, 2021