Something if-fi
We often need ways to branch the execution in our scripts. Do one thing or another based on a condition. A simple way to to this is with the if-then syntax.
if [ condition ]; then
# execute something
fi
# continue here
Read as: if condition is met then execute something.
Maybe we want to check that certain conditions are met before executing the
command.
Say we have a script that requires two arguments.
We can bail out with a helpful error message if not exactly two are given using an if.
#!/bin/bash
if [[ "$#" -ne 2 ]]; then
echo "Usage: $0 <username> <password>"
exit 1
fi
# Continue with login
The script will exit with a helpful error message if not exactly two arguments
are given.
The -ne part means not equal.
There is also -eq for equal, -gt for greater-than and -lt for less-than.
You can compare strings with == for equal and != for not-equal.
You can even make conditions based on regular
expressions with =~.
See
here
for more details.
[!CAUTION] Don’t write or use scripts that accepts a password as argument like above. This is because the password will then end up in your command history (
.bash_history).
A safe way of accepting password input is:
read -s -p "Password: " password
Then access it through the $password variable.
If..elif..Else statement
We can use elif to specify alternative conditions.
And else for commands to run if neither conditions match.
Here is an example:
#!/bin/bash
if [[ "$#" -eq 1 ]]; then
read -s -p "Password: " password
elif [[ "$#" -eq 2 ]]; then
username=$1
password=$2
else
echo "Usage: $0 <username>"
exit 1
fi
echo "Login..."
Exit codes
Also, and interesting thing to note with exit 1 is that we exit with a
exit-code of 1.
Exit codes are used for error handling.
All exit-codes except 0 is considered an error.
If you just type [[ 1 -ne 1 ]] directly in bash, you get an exit code of 1,
signaling that the conditions isn’t true.
You can check the last exit code with:
echo $?
Challenge
Create a script that checks if it is Christmas-eve.
Hint: Run “man date” in your terminal.