Conditional command execution

-it is possible to specify that a command in
a script will only run if particular condition Is met

- such conditions are always expressed in terms of
the exit status of another program, as follows:

Command1 && command2

Means that command2 will only run if command1
Completes with an exit status of 0



Command3 || command4

Means that command4 will only run if command3
completes with an exit status that is not 0

For example:
ls file1 && cp file1 ./tmp
cp abc xyz && echo The file was copied OK
diff fileA fileB || echo The fiels are different
ls file2 || exit


-The only problem with these constructs is that they are
very limited:

- You can only perform one command if the condition is met
(however, it is possible to group commands)
- You cannot specify a second command to be run
If the condition is not met


The if Statement

-A much more powerful (and readable) shell
programming construct is the if statement

-It's form is as follows:

If command1
Then
Command2
Command3
....
Fi

For example:

If diff file1 file2 > /dev/null
then
echo The files are the same
rm file2
fi



The else clause
-The if statement is a powerful language construct, but
we still have not seen a way to either:
--- execute commands on the condition that a given command
returns a non-zero exit status
---execute commands if a given condition is not met

-There is an optional component to the if statement, known as
the else clause, that will facilitate solutions to both of these problems,
as follows:

if command1
then
one set of commands
else
another set of commands
fo

For exaple:
if diff file1 file2 > /dev/null
then
echo the files are the same
rm file2
else echo The files are different!
diff file1 file2
fi


-We now have a way to execute commands if a given command
returns a non-zero exit status:

if ls file1 > /dev/null
then
: # ":" is the "do nothong" command
else
echo The file doesn't exist - exiting ...
exit
fi




The elif clause

-Often we need to write a conditional code construct in which there are
more than two mutually exclusive options
-The if statement also offers the elif clause (short else if), as follows:

if command1
then
command set 1
elif command2
then
command set 2
else command set 3
fi


For example:
if ls $file > /dev/null 2>&1
then
echo Sorry, the file already exists
elif who > $file
echo $file now contrains the user list
else Could not create $file
fi

- The elif clauses can be repeated indefinitely
(however, there can only be one else clause)

Comments

Popular posts from this blog

HAproxy logging

teamcity Automatic Agent Start under Linux

NFS mount add in fstab _netdev instead of default | firewall-cmd --list-all