AI Hints
Home›Linux Tutorial›Decisions and Loops
Linux · Lesson 104 of 120

More Choices

Elif and numbers.

⏱ 2 min read▶ Video at 2:19:31🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Sometimes there are more than two possibilities. ELIF, short for else if, lets you check one condition after another, until one is true.

More Choices
From the video: More Choices
  • More than two paths
  • elif means else if
  • Checked in order

vote.sh

The script reads an age. Dash GE means greater than or equal. Eighteen or more, you can vote. Otherwise, ELIF checks a second condition, sixteen or more. And else catches everything left.

nano vote.shbash
#!/bin/bash
read -p "How old are you? " age
if [ "$age" -ge 18 ]; then
  echo "You can vote."
elif [ "$age" -ge 16 ]; then
  echo "Nearly there!"
else
  echo "Not yet."
fi

Three answers

We run it three times. Twenty one can vote. Seventeen is nearly there. And twelve, not yet. Only one branch ever runs, the first one whose test is true.

Terminal
./vote.sh
How old are you? 21
You can vote.
./vote.sh
How old are you? 17
Nearly there!
./vote.sh
How old are you? 12
Not yet.

Combining tests

You can join tests together. Double ampersand means and, so both must be true. Double pipe means or, so either can be true. And an exclamation mark means not. For example, if not dash D backups, make the folder.

keyvalue
[ a ] && [ b ]both true
[ a ] || [ b ]either true
[ ! -d dir ]not a folder
elifcheck another

Summary

ELIF adds more choices, checked in order, and only the first true one runs. And, or, and not combine tests. Next, doing things again and again, with loops.

Key takeaways
  • if … elif … else … fi
  • -ge -le
  • && || !
Next up: For Loops — repeat for each item