Nested Ifs: Else Do Another Thing If Another Expression Is
Nested Ifs: Else Do Another Thing If Another Expression Is
if <command1> ; then
<some commands>
elif <command2> ; then
<some other commands>
elif <command3> ; then
<yet other commands>
…
else
<other commands>
fi
One of the easiest ways of doing this is by using elif (short for else if)
for all the alternative expressions we want to test.
Why would we do this? Imagine that we had a shell script that could do
several different things and the decision as to which it should do was made
by the user specifying different arguments on the command line. We might
want our script to have the following logic: if the user said “a” do this, else if
they said “b” do that, else if they said “c” do something else, and so on,
ending with else if they said something that was none of the previous things
say “I don’t know what you are talking about”.
There are better ways to do that than using this sort of if statement which
involve a construct (case) and a shell builtin command (shift) that we will
cover later today.
Version: 2019-02-26 10
More tests (1)
Test to see if something is true:
[ <expression> ]
or: test <expression>
where <expression> can be any of a
number of things such as:
[ -z "a" ]
[ "a" = "b" ]
[ -e "filename" ]
[email protected] Simple Shell Scripting for Scientists: Day Four 11
As well as the (integer) arithmetic tests we met on the second day of the course,
there are a number of other tests we can do. They fall into two main categories:
tests on files and tests on strings. There are many different such tests and we
only list a few of the most useful below:
–z "a" true if and only if a is a string whose length is zero
"a" = "b" true if and only if the string a is equal to the string b
"a" == "b" true if and only if the string a is equal to the string b
"a" != "b" true if and only if the string a is not equal to the string b
–d "filename" true if and only if the file filename is a directory
–e "filename" true if and only if the file filename exists
–h "filename" true if and only if the file filename is a symbolic link
–r "filename" true if and only if the file filename is readable
–x "filename" true if and only if the file filename is executable
You can often omit the quotation marks but it is good practice to get into the habit
of using them, since if the strings or file names have spaces in them then not
using the quotation marks can be disastrous. (Note that string comparison is
always done case sensitively, so “HELLO” is not the same as “hello”.)
You can get a complete list of all the tests by looking in the CONDITIONAL
EXPRESSIONS section of bash’s man page (type “man bash” at the shell
prompt to show bash’s man page.)
Version: 2019-02-26 11