Amazing Bash Script Options
Dec 8 2021Linux has become the de-facto operating system these days especially for servers. Most of us have been using Linux operating systems almost every day and it has become a need to understand this OS from it’s very basic to it’s core. Though there are many tutorials, posts available online which could help us in learning more about Linux, in this post I’ll be discussing few not so popular and some very common syntax being used for bash scripting.
Bash script begins
In majority of the bash scripts you might have read or maybe written, the below three lines:
set -o errexit
set -o pipefail
set -o nounset
set -o errexit
is also equal to set -e
which means that if in case
any of the commands in our bash script fails, the entire script’s
execution will fail. This option is very help to be used when you have
multiple scripts running as part of automation or delivery pipelines.
set -o pipefail
is used to exit out of your script if any of the
pipe commands fail during the bash script’s execution. Or else you’ll
be greeted with wrong exit codes when the code is being piped.
set -o nounset
is also equal to set -u
which means that the script
will exit if any of your variables are not set.
Using pushd and popd commands
Often times, you would’ve seen two commands pushd
& popd
being
used in any of the bash script (
example). These
two commands are shell builtins which allows to manipulate the usage
of directory stack. These are used to change the directories and
return to the same whenever required.
Let’s say we are currently in a directory called k8s_practice
,
$ pwd
~/k8s_practice
Now, I’ll pushd to another directory called git-clones
,
$ pushd ~/git-clones
~/git-clones ~/k8s_practice
$ pwd
~/git-clones
And upon using popd
, we can simply pop the present directory and
will return to the previous k8s_practice
dir,
$ popd
~/k8s_practice
$ pwd
~/k8s_practice
These commands are very useful when you plan to quickly change between directory stack in your bash script.
Beyond infinity: /dev/null
I bet you’d have seen the following syntax: in many bash scripts,
» /dev/null 2>&1
This syntax is basically a shorter way of silencing a process. One can even write it as: 2>&
» /dev/null redirects standard output (stdout) to /dev/null, which eventually discards it. /dev/null is that dark place (special file) of linux OS such that whatever is written into it, is eventually discarded into void or sent into a black hole. And, 2>&1 redirects standard error to standard output which eventually discards it. & here indicates a file descriptor as there are three - standard input, output and error.
So, these were few basic pointers which I hope you’ll keep in mind or maybe pay attention to while writing your next bash script.