Chapter 5: Comparing Values

Bash has a built-in command called test, which is also represented by single brackets, [ ].

For example, [ -d ~ ] will test if my home directory is a directory. It will return an exit status of 0 (success) or non-zero number (fail). We can use the value of $? to read the value of return status.

Comparing Numerical Values

To test numbers, use eq, -ne, -lt, -le, -gt, -ge.

1 if [ $# -eq 0 ]; then
2 	read -p "Enter a username: " user_name
3 else
4 	user_name="$1"
5 fi

Comparing Strings

Use == and != to compare strings. We must use a single space before and after these operators.

 1 "$string1" == "$string2"
 2 "$string1" != "$string2"
 3 
 4 # Example
 5 if [ "$password" != "$password_check" ]; then
 6 	echo "Passwords do not match"
 7 	# Exit to ensure nothing else is executed: 1 is Error, 0\
 8  is for success
 9 	exit 1
10 fi

Extended Test

Extended test uses double brackets, [[ ]], and allows us to use more than one expression within a test, for creating a little bit more complex logic.

For example, below, we are checking if my home directory is a directory and whether the bash binary exists:

1 [[ -d ~ && -a /bin/bash ]]; echo $?

Similarly, we can use || for OR operation, which executes the next command only if the previous command fails.

Extended test also allows us to use regular expression. Below we are testing if “cat” starts with c: [[ "cat" =~ c.* ]]; echo $?

It is recommended to use extended tests as a best practice.