# This shell script demonstrates basic control flow: conditional # statements, and how to write some basic conditions that you may # want to test. The basic structure is simple: ‹if condition; then # commands; else commands; fi›. We can either use semicolons or # newlines. Different people prefer different styles. # The ‹condition› part of the ‹if› statement is a command. If the # command is successful (i.e. if it returns exit code 0), the ‹then› # branch of the conditional is taken. Otherwise, the ‹else› branch # is. The ‹else› branch is optional. echo 'we first try some if statements and the ‹test› program' echo # The program that is most often used in ‹if› conditions is called # ‹test›. You can use it to check basic properties of files # (existence, whether they are regular files or directories, if one # file has been modified more recently than another and so on). It # can also test properties of numbers (basic relational operators) # and strings (emptiness and equality). A few examples follow. if test -e file.txt; then echo file.txt exists fi if test -f file.txt; then echo file.txt exists and is a regular file fi if test 3 -gt 4; then echo "3 is greater than 4" fi if test 3 -lt 4; then echo "3 is less than 4" fi # There is another way to call ‹test›, and that is ‹[›. Yes, there # is a command with the name ‘left square bracket’. It is usually a # (sym)link to ‹test›. In some shells, it is also built-in (both # ‹test› and ‹[›). if [ -e file.txt ]; then echo file.txt still exists else echo file.txt does not exist fi # The closing square bracket is an argument to ‹[› and it is # required: ‹[› will complain if you don't supply it, like this: # # [: the last argument must be ']' echo # For more details, see ‹man test›. There are two other utilities # that sometimes come in handy, called ‹true› and ‹false›. Let's try # running them. I will also mention a new variable (this one is # quite special) called ‹?›. It holds the exit code of the last # executed command. It is not possible to assign your own values # into this variable. true echo exit code from true: $? false echo exit code from false: $? if true; then echo "if true: then branch"; else echo "if true: else branch"; fi if false; then echo "if false: then branch" else echo "if false: else branch" fi # I would suggest you run this script now, and also make sure that # ‹test -f› does what we think it does: # # $ sh test.sh # $ touch file.txt # $ sh test.sh # Let's move on: # # $ micro chaining.sh