Using && and || in Bash Scripts

I write about Bash so often you might start to think it’s all I do. It’s not, but considering I spend a good portion of my day in the terminal, I’m always on the look out for ways to make it a more efficient experience.

Recently, I came upon a simple trick for bash scripts that just has to be shared. It involves the operators && (AND) and || (OR). In most cases, && and || are used for evaluation purposes, resulting in a boolean value (true or false).

In most languages, this would look something like this:

# Using Ruby for this example
foo = true
bar = false
if foo && bar; end # returns false; && requires both expressions to evaluate to true
if foo || bar; end # returns true; || requires only one expression to evaluate to true

The && Operator

Since we know that an && requires both expressions to be true, we can use this knowledge to chain bash commands that we only want to run in succession if the first command was successful. For example:

cd foo && touch bar.html

If the terminal is able to successfully cd into the directory foo, then it will attempt to create the file bar.html. If it fails, no attempt at file creation will be made.

The || Operator

In other circumstances, we might want to try one command and then another if the first fails. In this case, the || operator is our friend. I have specifically used this in a bash alias I’ve made for deploying a site. Depending upon what version of Capistrano is being used in a project, the terminal command syntax is different. Thus, we simply try one, and if it fails we try another.

Putting Them Together

So, you can see that you can quickly use these to construct larger scripts that can do a rudimentary form of error handling without a lot of effort. Often, I need to deploy the same feature branch of code to multiple environments. I made a bash function using the && and || operators like I’ve laid out here to do just that with one short command.