Y NOT — Brush Up Bash Shell Scripts

Operating System (OS) has two means of communication channels for users to interact with them— GUI (Graphical User Interface) and CLI (Command Line Interface).

In case of Linux based OS, shell commands are used on CLI. GUI comes up with additional RAM Consumption and hence some system like Routers (built by CISCO operating on customized OS based on Linux) have only CLI enabled.

Similarly, Hypervisor (also known as Virtual Machine Monitor VMM) also have this OS with limited features only on CLI to improve performance.

The shell is an interactive interface that allows users to execute other commands and utilities in Linux and other UNIX-based operating systems. We have many types of Shell like Bash (Bourne Again Shell), C Shell (csh), Korn Shell (ksh), Z Shell (zsh) etc and bash is something that is widely used across.

The script is a series of commands that will be run together. The way of sequencing and executing multiple commands in order at a single triggering point is known as scripting. This scripting facilitates the scope for many automation use cases.

As a recommended best practice, any shell command should return exit codes that tells whether the state of command execution status (general norm for success is 0 and for failure it is non zero error codes). By use of “?” (internal variable) which is pre-programmed in shell, we would be able to retrieve the exit code of most recently executed command.

Which Command — It is used to locate the executable file associated with the given command by searching it in the path environment variable.

Man Command — Used to display the user manual of any command that we can run on the terminal. It provides a detailed view of the command which includes Name, Synopsis, Description, Options, Exit Status, Errors etc

Any bash shell script needs to have the first line as “#! /usr/bin/bash” where the path post #! specifies the location of bash executable. This first line (#!/bin/bash or #!/bin/sh) has a name. It is known as ‘she-bang‘(shabang). This derives from the concatenation of the tokens sharp (#) and bang (!). It is also called as sh-bang, hashbang, poundbang or hash-pling.

In simple words, the she-bang at the head of the script tells the system that this file is a set of commands to be fed to the command interpreter indicated. Linux/Unix-like operating systems has variety of shells and each of script header lines call a different command interpreter.

#!/bin/bash :Executes the script using the Bash shell.

#!/bin/csh -f :Executes the script using C shell or a compatible shell.

When running commands, the shell takes the command input, searches for the command in the available command paths in the pre-configured PATH environment variable. We can give multiple paths for the shell to search in the PATH variable by separating them using colon (:) symbol.

To allow our scripts to run from anywhere on the system, we need to update the PATH variable with the full path for our script file. For example ⇒

PATH=/wsshell:$PATH #Update current PATH variable with one more location /wsshell
  • Note that the update to the PATH variable is not permanent by this method. To make this permanent, we need to specify the updating command in the /root/.bashrc file, as this file is always run during boot time and before the bash shell starts working. ⇒
#Put the following line in the .bashrc FilePATH=/wsshell:$PATH #Update current PATH variable with one more location /wsshell

Basic Example — To Accept Name And Display User Specific Greeting Message

Input arguments to shell script are accepted/retrieved using $ symbol and order like first input argument as $1, second input argument as $2 etc

To pass multiple values for the same argument, use $@ instead of $1 as below and loop through the array

To pass the output of command 1 as input to command 2, please use the command 1 within $(command 1)

eg x=$(date) where date gets executed first and its output is stored to variable x. Let us see one use case of reading a csv file containing multiple names. We will retrieve them as array and loop them to print their names

Input/Output Redirection Command :

> (Output Redirection) — command on left side of this operator gets executed and written to file on right side (eg date > f.txt)

< (Input Redirect) — command on right side of the operator gets read and fed as input to command on left side of the operator (eg tr ‘a-z’ ‘A-Z’ < /etc/passwd). This reads contents from etc/passwd file and transforms/converts all lower case letters to upper case letters.

Logical Operations:

To check equality, == or -eq is used to check equality, -ge is used to compare greater than or equal to, -le for less than or equal to, -lt for less than.

Cut Command —Used for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text. For eg, etc/passwd file has user details like username, home directory path etc. Based on : delimiter, we will extract the home directory for a given user ‘ec2-user’ as below

cut -d “:” -f1 /etc/passwd

where -d is for delimiter param and -f followed by column number that we want to extract

Tar Command — It is used to create Archive and extract the Archive files.We can use Linux tar command to create compressed or uncompressed Archive files and also maintain and modify them.

tar [options] [archive-file] [file or directory to be archived]

tar -cf filename.tar sourceDirectory

Switch Case Statement — The bash case statement is generally used to simplify complex conditionals when you have multiple different choices. Using the case statement instead of nested if statements will help you make your bash scripts more readable and easier to maintain.

Hope you enjoyed the article!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store