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
$ echo "hello there"; echo "how are you"
hello there
how are you
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
$ cat .bash_profile && echo "this is my profile"
cat: .bash_profile: No such file or directory
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"
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.
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
#!/bin/sh
[ -z "$EDITOR" ] && EDITOR=nano
echo $EDITOR
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.