Shell Script Indentation
Indenting your code
When you write statements such as while or if, you should indent your code. This involves lining up the keywords for your
statement and indenting the commands inside the statement. For example, with an if statement, format the code in the following
way: if [ "$answer" = "yes" ] then echo "You answered yes" else echo "You did not answer
yes" fi
The keywords of the if
statement, if, then, else, fi
are easily seen in the statement. The statements
inside, the two echo
commands, are indented by two spaces. If you have one statement inside another, keep indenting.
The following sample code shows several if
statements nested inside a while
loop. while [ $answer !=
"quit" ] do echo "enter a number: " read num if [ "$num" = 1 ] then echo "you entered a
one" fi if [ "$num" = 2 ] then echo "you entered a two" fi done
It is easy to see the do and done statements in the while
loop above. This makes it easier to understand what your
code is doing and easier to locate the beginning and end of this loop.
It is clear that the if
statements are inside the while loop because they are indented two spaces inside the loop.