OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

if

Using the shell, we can code the logic above as follows:



x=5


if [ $x -eq 5 ]; then echo "x equals 5."

else

echo "x does not equal 5."

fi

x=5


if [ $x -eq 5 ]; then echo "x equals 5."

else

echo "x does not equal 5."

fi


or we can enter it directly at the command line (slightly shortened):


[me@linuxbox ~]$ x=5

[me@linuxbox ~]$ if [ $x -eq 5 ]; then echo "equals 5"; else echo "does not equal 5"; fi

equals 5 [me@linuxbox ~]$ x=0

[me@linuxbox ~]$ if [ $x -eq 5 ]; then echo "equals 5"; else echo "does not equal 5"; fi

does not equal 5

[me@linuxbox ~]$ x=5

[me@linuxbox ~]$ if [ $x -eq 5 ]; then echo "equals 5"; else echo "does not equal 5"; fi

equals 5 [me@linuxbox ~]$ x=0

[me@linuxbox ~]$ if [ $x -eq 5 ]; then echo "equals 5"; else echo "does not equal 5"; fi

does not equal 5


In this example, we execute the command twice. Once, with the value of x set to 5, which results in the string “equals 5” being output, and the second time with the value of x set to 0, which results in the string “does not equal 5” being output.

The if statement has the following syntax:

if commands; then

commands

[elif commands; then

commands...] [else

commands]

fi

where commands is a list of commands. This is a little confusing at first glance. But be- fore we can clear this up, we have to look at how the shell evaluates the success or failure of a command.


Top OS Cloud Computing at OnWorks: