Linux Classes
Linux Training
* Linux Classes *

LINUX CLASSES - PROGRAMMING

Where's the Logic in That?

So far, all of our sample scripts have been just a sequence of commands executed one after the other. We haven't added any if/then/else logic or used looping constructs to control the flow of the program.

Note: If you've never written or seen a computer program in your entire life, the rest of this section will probably seem a bit foreign. But try to follow the examples; then test and modify them on your own to get the hang of it.

Conditional Operations

Let's look at the if/then/else construct in a Bash shell script and see how to control the flow of a script with conditional logic. The general form of if/then/else is shown here, with the actual syntax shown in boldface and the parts you must supply in normal type:

if [ condition is true ]
then

execute these commands

else

execute those commands

fi

The else clause is optional, but you must end the construct with the fi command. You can also have nested if clauses by using the elif command like this:

if [ condition1 is true ]
then

execute these commands
elif [
condition2 is true ]
then

execute these commands
else

execute those commands
fi

So what kind of conditions can we test for? If you're dealing with numbers, here are the conditional expressions you can use. In other words, any of these expressions can go inside the brackets on the if or elif statement:

num1 -eq num2 True if num1 equals num2.

num1 -ne num2 True if num1 is not equal to num2.

num1 -lt num2 True if num1 is less than num2.

num1 -gt num2 True if num1 is greater than num2.

num1 -le num2 True if num1 is less than or equal to num2.

num1 -ge num2 True if num1 is greater than or equal to num2.

If you're comparing character strings, these are the valid conditional expressions:

str1 = str2 True if str1 and str2 are identical.

str1 != str2 True if str1 and str2 are not identical.

-n str1 True if str1 is not null (length is greater than zero).

-z str1 True if str1 is null (length is zero).

You can also test certain file conditions, such as whether or not files exist, the type of file, and so on. Here are the conditional expressions for files:

-f somefile True if somefile exists and is an ordinary file.

-d somefile True if somefile exists and is a directory.

-s somefile True if somefile contains data (the size is not zero).

-r somefile True if somefile is readable.

-w somefile True if somefile is writable.

-x somefile True if somefile is executable.

And finally, here are the logical operators, for performing tests that involve and, or, and not conditions.

cond1 -a cond2 True if both cond1 and cond2 are true.

cond1 -o cond2 True if either cond1 or cond2 is true.

! cond1 True if cond1 is false.

Some if/then/else Examples

Here are some examples using the conditional expressions just listed. Note that the spaces on either side of the square brackets are not optional!

if [ $carprice -gt 20000 ]
then

echo 'Too rich for my blood.'

else

echo 'Can you get that model in blue?'

fi


if [
$maker = 'Buick'
]
then

echo 'Have you driven a Ford lately?'

fi


if [
-r $1 -a -s $1
]
then

echo "The $1 file is readable and contains data."

fi

The case Statement

Bash provides a case statement that lets you compare a string with several possible values and execute a block of code when it finds a match. Here's an example of the case command, with the syntax shown in boldface and the parts you would supply in normal type:

case $1 in
-a
)
commands;;
-f
)
commands
;;
*)
commands
;;
esac

In this example, if the value of $1 was -a, the first block of commands would execute. If the value of $1 was -f, the second block of commands would execute. Otherwise, the third block of commands, following the asterisk clause, would execute. (Think of the asterisk as meaning "match anything.")

You can put as many commands as you need in place of commands in the sample, but be sure to end the block with a double semicolon. Only the first matching block of commands will execute in a case statement, and you must signal the end of the construct with the esac command.

Previous Lesson: Shell Script Variables
Next Lesson: Shell Script Looping

[ RETURN TO INDEX ]

Comments (most recent first)

Bob Rankin     (16 Jul 2010, 15:07)
@hello_world - You might want to check the "Homework Helper" website. :-)
hello_world     (16 Jul 2010, 00:44)
Write a program which will output greetings ( Good Morning, Good Afternoon, Good Evening to user based on the time the script is run.
( Use case Statement in script)
Vishnu     (09 Jul 2010, 00:59)
How to find the existence of similar files.. like files having a particular date template
If [ -e *date* ] is giving error ,,too many arguments
ab     (04 Jul 2010, 13:48)
why shell reverses the meaning of true or false compared to other languages??
Kumar Piyus     (21 Jun 2010, 11:25)
The information is to the point and very easy to understand. Really nice.
abhinav narain     (09 Jun 2010, 12:16)
[ -z STRING ] option returns true,if the length of the string is zero
abhinav narain     (09 Jun 2010, 09:10)
What is -z option used for ?
i cant find it in the websites i visited
George Lazarides     (26 May 2010, 13:14)
Nice page! Your site is a great reference that I'll keep bookmarked for future use!

But I think you forgot an option:
-e somefile True if somefile exists.

if [ -e /var/logs/error.log ]
then
echo 'There is an error log.'
else
echo 'No errors today.'
fi
Roberto     (17 Apr 2010, 03:19)
VAR=$(COMMAND_LIST)
How I can test if the commands in COMMAND_LIST are run correctly?
Bob Rankin     (18 Mar 2010, 20:49)
You are right! Fixed now.
Luis     (18 Mar 2010, 18:32)
better if it was
if [ -r $1 -a -s $1 ]
not
if [ -r $1 -a -s $2 ]
right?
Pedro Oliveira     (26 Feb 2010, 09:16)
Like it! It helped me on a shell script. Thanks!

*Name:
Email:
Notify me about new comments on this page
Hide my email
*Text:
 

Ask Bob Rankin - Free Tech Support
<Send This Link to a Friend>         <Bookmark This Page>


Copyright © by Bob Rankin
All rights reserved - Redistribution is allowed only with permission.