How to use conditional execution of command lists

Any builtin command, expression, or function, as well as any external command or script can be executed conditionally using the &&(and) and ||(or) operators.

For example, this will only print the current directory if the cd command was successful.

cd my_directory && pwd

Likewise, this will exit if the cd command fails, preventing catastrophe:

cd my_directory || exit
rm -rf *

When combining multiple statements in this manner, it’s important to remember that (unlike many C-style languages) these operators have no precedence and are left-associative.

Thus, this statement will work as expected…

cd my_directory && pwd || echo "No such directory"

But this will not (if you’re thinking if...then...else)…

cd my_directory && ls || echo "No such directory"

It is the ls, not the cd, that is the previous command.

Why use conditional execution of command lists

Conditional execution is a hair faster than if...then but its main advantage is allowing functions and scripts to exit early, or “short circuit”.