There are several ways to make "if - then" decisions in shell scripts. The most direct is the "if -then" construct itself:
if [ "$x" ] then echo x is not blank else echo x is blank fi
That can also be written as
if test $x then echo x is not blank else echo x is blank fi
But watch out for quoting - if $x had never been set at all, that second method would be fine, but if it were "foo bar", the script would fail without quotes. The same warning applies when testing against a value:
if [ "$x" = "foo" ] then echo "x is set to foo" else echo "x is not set to foo" fi
Forgetting to quote $x will cause unexpected failures. The "test" method has many more possibilities ("man test" will show them).
Another construct you'll often see is this:
somecommand && echo "Success" || echo "Failure"
But watch out: there's a trap in there you may not see. The line above will probably always do what you think it should because 'echo "Success"'" is unlikely to fail. But if we use some different commands, it's easy to see where this could go wrong:
date && true || echo "Fail" # prints the date date && : || echo "Fail" # a better way to do that false && date || echo "Fail" # prints "Fail" date && false || echo "Fail" # prints the date and "Fail"
The && and || are useful tools, but be careful when using them together.
Another way to test is the case statement:
while : do echo "Please choose Y, N, or Q";; read akey case $akey in [Yy]) echo "Yes";break;; [Nn]) echo "No";; [qQ]) exit 0;; *) echo "Only Y, N or Q" esac done echo "Thanks";
Got something to add? Send me email.
More Articles by Tony Lawrence © 2012-07-17 Tony Lawrence
Whenever the literary German dives into a sentence, that is the last you are going to see of him till he emerges on the other side of his Atlantic with his verb in his mouth. (Mark Twain)