Coding for All
Lesson 5: Making Decisions
Making Decisions Do one thing or another, depending on a test.
1#!/bin/bash
2age=10
3if [ $age -ge 8 ]; then
4 echo "Old enough to ride!"
5else
6 echo "Maybe next year."
7fi
Terminal
$ ./ride.sh
Old enough to ride!
Every line, explained
#!/bin/bash
This first line is called the shebang (from "hash bang", the # and ! it starts with). It is not a comment: it tells the computer which program should read the rest of the file. #!/bin/bash means "run this with bash". Every bash script starts with this exact line.
age=10
Variables work exactly as they do at the prompt: name on the left, = with no spaces around it, value on the right. Scripts use them constantly, because a value written once and used many times is a value you can change in one place.
if [ $age -ge 8 ]; then
if runs the lines underneath it only when the test in the square brackets is true. Mind the spaces: bash needs a space after [ and before ], because [ is really a command, not punctuation. Inside the brackets, -ge means "greater than or equal to". Bash uses these little word-flags for numbers: -eq (equal), -ne (not equal), -lt, -le, -gt, -ge. then marks the start of the "if it was true" part, and fi (that is if spelled backwards) marks the end. Every if needs its fi. (The semicolon is just a way of writing then on the same line.)
echo "Old enough to ride!"
This line runs only when the test was true. The indentation is for human eyes only: bash does not care, but everybody who reads your script will.
else
else is the "otherwise" branch: it runs when the test was false. Exactly one of the two branches runs, never both.
echo "Maybe next year."
And this line runs only when the test was false. With age set to 10, you will never see this one.
fi
then marks the start of the "if it was true" part, and fi (that is if spelled backwards) marks the end. Every if needs its fi. Without fi, bash reads to the end of the file still waiting to be told where the if stops.