Replacing "if" when writing a Bash Script
2 min read

Replacing "if" when writing a Bash Script

Replacing "if" when writing a Bash Script

Believe it or not, 95% of the time you do not need if statement. Most of the time you can always make do with some other alternatives to keep your script clean and efficient.

Here are some short tips which you can adopt straight away.

Chaining commands together using ;

Before we jump into the "if" replacement, let's take a look at how we can shorten our scripts by chaining commands together. So instead of entering two commands separately across two lines, we can reduce to one single line. The second command will run after the first command regardless if the first command runs successful or not.

$ echo "hello there"
$ echo "how are you"
hello there
how are you
two commands in two lines
$ echo "hello there"; echo "how are you" 
hello there
how are you
two commands in one line

But there is a problem with this approach, what if we want to run the second command only if the first one runs successfully? Let's welcome &&.

Using && as an if replacement

To make sure that the second command executes only if the first command runs successfully, use &&. Essentially, this can be an if replacement. Every time you need something to be completed first, append the && operator and continue with the rest of your command.

$ echo "hello there" && echo "how are you"
hello there
how are you
chaining two commands together using && has similar effect as ;
$ cat .bash_profile && echo "this is my profile"
cat: .bash_profile: No such file or directory
however, if the first command does not execute successfully, the second command will not run

Use || as a replacement for else

Sometimes we want to be alerted if a command doesn't run. This can be done using the || pipe operator. With this, the second command only runs when the first doesn't - allowing us to be alerted or clean up the mess during failure.

$ cat .bash_profile || echo "file does not exist"
second command runs only if the first fails to run

Run both commands concurrently using &

By now you would have realised that all three commands introduced above run in sequence. But what happens if you want to launch commands concurrently? This time, you can use the single & operator to chain up commands and they will all be fired in parallel.

$ sleep 5 & echo "All done."
[1] 4988
All done.
both commands will run concurrently

Putting them together

To sumarise, you can avoid using the if keyword and save a few lines by using the && and || operator.  

#!/bin/sh

if [ "$EDITOR" = ""]; then
	EDITOR=nano
fi

echo $EDITOR
this is an ugly way of implementing
#!/bin/sh

[ -z "$EDITOR" ] && EDITOR=nano

echo $EDITOR
works exactly the same way but more elegant

That's all, time to write better bash script!

Reference

This post is writing with heavy reference to this youtube video. Full credit goes to the author.