# Conditional Expressions

Conditional expressions

Earlier in the week, we look at how to assign values to variables. Now, we’re going to start looking at how we can compare them. To do this, we use conditional expressions.

Modern Bash syntax for conditional expressions encases our comparative expression inside double square brackets ([[ and ]]).

The syntax for this is:

[[ option arg1 ]]

or

[[ arg1 operator arg2 ]]

A conditional expression returns a Boolean value i.e. true or false. If the condition is met, it will return true and if not, false.

It’s worth noting that the spacing is important. Here are some examples of valid and invalid conditional expression syntax.

Valid:

[[ -f ${file} ]] Invalid: [[ -e file]][[-e file]][[-efile]] ## File and variable operators When we process files in our Bash scripts, it is often useful to check that they exist or whether they’re empty before the rest of our script proceeds. File operators allow us to perform checks on files and give us the opportunity to handle errors gracefully. Below are some of the most commonly used file operators. Returns true if the file exists: [[ -e${file} ]]

Returns true if the file exists and is a directory:

[[ -d ${directory} ]] Returns true if the file exists and is a regular file: [[ -f${file} ]]

Returns true if the file exists and is readable:

[[ -r ${file} ]] Returns true if the file exists and has a file size > 0: [[ -s${file} ]]

We can also use conditional expressions to perform sanity checks on our variables.

For example, checking whether a value has been assigned to a particular variable (e.g. var):

[[ -v ${var} ]] Or, to check that the variable length is greater than 0: [[ -n${string} ]]

Or, that the length of the variable is 0: