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.
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
&& as an
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.
|| as a replacement for
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.
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.
Putting them together
To sumarise, you can avoid using the
if keyword and save a few lines by using the
That's all, time to write better bash script!
This post is writing with heavy reference to this youtube video. Full credit goes to the author.