Understanding BASH Command Line
Unlocking the potential of Open-Source most popular shell
What is a Shell
After combing the internet for lengthy hours, I finally found a definition that best describes what a shell is. Thanks to Dartmouth college for putting forth a very simple and concise definition. According to their CS 50 lecture notes; "The shell is the Linux command line interpreter, it provides an interface between the user and the kernel and executes programs called commands". In summary, the shell provides you with an interface to communicate with the operating system.
What is a Bash Shell
The Bourne Again Shell (BASH) is a simplified and enhanced version of the Bourne Shell distributed with the GNU/Linux operating systems. It's an open-source GNU project written by Brian Fox in 1989 and offers both programming and interactive uses.
On Linux, bash commands are stored in the /usr/bin/bash directory. This location is part of the system's PATH.
Most Linux and Unix OS use bash by default. To confirm this you can run the echo $0 command. This command returns an output that will show the default shell being used.
BASH Scripting
BASH is considered powerful because of its scripting ability. Any command that can be run on the shell can also be put into a plain-text file and have bash run it for you as a script. The fact that nearly everything on Linux can be run on the BASH shell promotes the belief that nearly everything can be scripted through BASH. Scripting opens up thousands of possibilities and gives the computer control to make things happen without you doing them yourself. This saves Linux users time and seamlessly eases workflow that nobody else thinks could be made simpler.
Bash scripting projects for your perusal
BASH Fundamentals
The numerous advantages offered by the use of BASH cannot be over-emphasized given the fact that it's also open source and free to use. To harness the powers of BASH, this article will help highlight some key components and commands which when mastered will give you BASH superpowers and leave you feeling like you have conquered the Night King.
- Variables
A variable is a temporary storage for a string or a number. They can easily be addressed as parameters that you can change the value of. Once a variable is assigned, it can be referenced at any point on the shell.
In BASH, we have two broad types of variables:
i. User-defined variables: These are variables that are assigned locally by the system user. These variables have a lifespan of the current user's shell. They could be anything set by the user and can be referenced at any instance on the current shell. They die off when the shell is expunged and needs to be reassigned again when a new shell is opened.
Setting a user variable:
name=trump
county=boston
points=7
ii. Shell variables: These are built-in variables that come pre-loaded into the bash shell. Shell variables come by default and are used to reference certain instances on the BASH shell. Most shell variables come in caps and cannot be altered by the local user.
Some common shell variables:
HOME: Absolute path to the current user's home directory
HOSTNAME: The name of the current machine
USER: The current user's username
P:S You can use the echo command followed by a dollar sign before the variable name to return the content of the variable on the command line.
echo $county
echo $HOME
- Command Substitution
Command substitution is used to directly reference the result of a command. It allows the output of any command to be channeled as an argument to another command. This feature comes in very handy when working with one or more commands
It has a syntax $(command)
It allows a degree of flexibility which can see commands used interchangeably.
An example is seen below,
currentdir=$(pwd)
The implication of this is, the content of the currentdir variable will be the ($pwd) command substitution. pwd is a command that print's the user's current working directory to standard output. Lets's say the current working directory is /home/trump/desktop. The value assigned to the currentdir variable will be; /home/trump/desktop. Anytime the currentdir variable is referenced it returns a value of the user's current working directory at that time.
- Arithmetic Expansion
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. It is simply used to perform mathematical calculations on the bash command line
It has a syntax $(( expression ))
An example is seen below,
echo $((5+7))
This command returns the value of the arithmetic computation to standard output. The result of the arithmetic expression returned to the standard output will be 12.
Another illustration of arithmetic expansion is seen in assigning variables.
x=3
y=$((x+5))
z=$((x*y))
In this example, the variable x is assigned a value of three. The variable y is assigned a value of the arithmetic expansion of x+5 and the variable z is assigned a value of the arithmetic expansion of x*y. Anytime the variables are referenced, it will return a value of the corresponding arithmetic expansion.
- List Operators
These are types of control operators that enable us to create a chain of commands that operate in different ways. The operators define how the commands will be executed one after the other. This could chain two or more commands in execution in a defined sequence.
Here is a picture showing how list operators help concatenate commands in BASH.
A simple illustration of this command is seen in this command chain below;
i. echo "home" ; ls /home/trump
This command will print the word "home" on the standard output and after that would list the contents of the home directory on the current shell.
ii. cat names.txt && echo "Joe" >> names.txt
This command will list the contents of the names.txt file and will then append the name Joe to the file. If the names.txt file is not present or not accessible, the command to append Joe to the file will not run. For the second command to run, the first command must run and return a zero exit status code.
- Test Operators
These are operators that can be used in bash to compare different pieces of information. Test operators act as comparators. In BASH, they compare one or more quantities and return either true or false for an answer. The shell can forward this answer returned for use by another command. Test operators can evaluate variables, arrays, strings or even files.
Here is an image showing some tet operators in BASH and their use case
Requisite BASH commands
In BASH, there are some intrinsic commands which allow the user to achieve complex programmable abilities on the command line. These commands make the BASH shell work as if it were a code builder. The use of such commands unlocks BASH programming and makes script building very powerful and endearing.
Read Command
The read command requests input from the user and save this input into a variable. It reads from standard input and assigns the user's value to a stated variable. Alongside the options it offers, it's a very friendly command that can be used interactively to assist the user get in inputs into the shell at runtime.
Here are some friendly options that can be used alongside the read command
Options
Usage
-p
Displays a prompt to users about what information they must enter
-t
Timeout if the user does not enter any value within “time” seconds.
-s
Hides the user's input from being seen in plain characters.
-N
Limit the response to exactly a certain number of characters
-n
Limits the length of the character in the text entered to a maximum number
An example is seen below,
read -t 30 -p "Input your first name within 30 seconds: " name
This command will enable the user to enter a name on standard input and the input will be saved to a variable called name. Anytime the name variable is referenced on the command line, it will return the value of the name entered by the user. The -t option will make this command timeout if the user fails to register input in 30 seconds. The -p option displays the markup info telling the user to enter a name within 30 seconds.
If Statements
If statements allow us to make decisions in our BASH scripts. It is the principal logic composer of the BASH shell. Composed of the keyword If, it heads over a conditional which will be executed if a certain condition is met. It starts and ends using the reserved words if and fi.
In BASH, the If statement implements logic by checking the exit status of a command and only runs the command if a certain condition is true. This can easily be branched into several conditions forming an elif
Here is a picture illustrating the use of if statements in BASH.
Loops
In BASH, a loop is an iteration statement that repeats a process to be executed. We can pair loops with conditional statements to perform some tricky and repetitive computations programmatically.
i. While Loops
While loops run a set of commands while a certain condition is true, hence their name.
You must ensure that the condition you provide the while loop does become false at some point to avoid an infinite loop.
Below is an illustration of a syntax of a while loop
An implementation of a while loop is also seen below,
This BASH program will request a number from the user and store the value in a variable termed num. A while loop will then kick in using a test operator and evaluate the number entered against 10. If the number is greater than 10 it will print the number on standard output. The number will be reduced by 1 for every iteration till it's less than 10. This will prevent an infinite loop.
ii. For Loops
To talk about for loops without talking about arrays will lead us astray. In BASH, the execution of a for loop is based on how it iterates over an array.
A for loop iterates over a list of words or elements and performs a set of commands for each element within that list, hence its name.
Variables can only store one piece of data at a time.
Arrays, however, can store multiple different values at the same time.
This makes arrays great tools for storing a lot of data in one place for batch processing.
Note: Bash uses spaces to separate values within an array, not commas. Each entry of an array is called an element and each element has its index. Indexes start from 0 and count up
An image illustrating arrays in BASH is seen below,
for loops are an amazingly powerful tool when coupled with arrays, as they allow us to create “assembly lines” that we can use for batch processing. This shows the syntax of the for loop operation.
Readarray Command
The readarray command converts what it reads on its standard input stream into an array. This command is very powerful in BASH programming. It can also convert input from command substitution or arithmetic expansion into an array.
Here is a syntax for the readarray command.
When the readarray command is employed and an array is created, a powerful for loop sequence can be constructed as seen below
In this for loop sequence, the readarray command is used to create an array called files from the contents of the file_list.txt. A for loop is then initiated for all members of the array. The loop iterates over every member of the array and if the file exists then the echo command prints out the file already exists, else the touch command will create the file and the file name will be printed to standard output.
Conclusion
Having put out these rudiments and key fulcrums of BASH, it is well to note that a whole lot can be achieved with proper use of BASH. Furthermore, there are still tons of use cases that can be harnessed from the advanced use of BASH. To this note, it is advisable to take up more learning on BASH and continue to dig deeper into open source's most powerful shell.
BASH Scripting Projects for your perusal
Recommendations for further learning;
Here are materials I would recommend if you would like to get started with bash. It's also a rich library for those building upon previous BASH knowledge.
Bash Mastery: The Complete Guide to Bash Shell Scripting by Ziyad Yehia