bash if else shorthand

shorthand if – else in bash

For some simple if-else conditions you may want to avoid having whole if; then; else; fi type of code. Instead, you can do it all in one bash if shorthand line. Here is how.

There are so called “and list” and “or list” constructs available in bash. You can use them to run commands consecutively and break only when condition is not met anymore – the condition for “and list” is true, for “or list” it’s false.

So the following (“and list”) will be broken at “ech 3” (note the typo):

[root@linux ~]# echo 1 && echo 2 && ech 3 && echo 4
-bash: ech: command not found
[root@linux ~]#

And the following (“or list”) is broken at first successfully run command, “echo 3”:

[root@linux ~]# ech 1 || ech 2 || echo 3 || ech 4
-bash: ech: command not found
-bash: ech: command not found
[root@linux ~]#

So by understanding how those lists work, you can now implement the if-else type of code in one line. Say you have this:

if [[ 1 -eq 1 ]]; then
  echo true
  echo false

You can change it into this bash if shorthand:

[root@linux ~]# [[ 1 -eq 1 ]] && echo true || echo false
[root@linux ~]# [[ 2 -eq 1 ]] && echo true || echo false
[root@linux ~]#

Once you get used to it, you will find it extremely suitable for many use cases when logical conditions are simple.

2 thoughts on “shorthand if – else in bash

Comments are closed.