# Understanding BASH Command Line

### 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](https://github.com/WilliamsOchu/Bash_Scripting_Projects)

### 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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678447044903/9fe686b0-4285-4d5b-887f-664b622273ff.png align="center")

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" &gt;&gt; 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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678448326087/f4f034d5-b2c1-4047-a35a-ace115c39cc1.png align="center")

### 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.

1. **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
    
    <table><tbody><tr><td colspan="1" rowspan="1"><p><strong>Options&nbsp;</strong></p></td><td colspan="1" rowspan="1"><p><strong>Usage</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p>-p&nbsp;</p></td><td colspan="1" rowspan="1"><p>Displays a prompt to users about what information they must enter</p></td></tr><tr><td colspan="1" rowspan="1"><p>-t&nbsp;</p></td><td colspan="1" rowspan="1"><p>Timeout if the user does not enter any value within “time” seconds.&nbsp;</p></td></tr><tr><td colspan="1" rowspan="1"><p>-s&nbsp;</p></td><td colspan="1" rowspan="1"><p>Hides the user's input from being seen in plain characters.&nbsp;</p></td></tr><tr><td colspan="1" rowspan="1"><p>-N&nbsp;</p></td><td colspan="1" rowspan="1"><p>Limit the response to exactly a certain number of characters</p></td></tr><tr><td colspan="1" rowspan="1"><p>-n&nbsp;</p></td><td colspan="1" rowspan="1"><p>Limits the length of the character in the text entered to a maximum number</p></td></tr></tbody></table>
    
    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.
    
2. **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.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678450491811/a078e47e-f4aa-4238-869e-48fc3b6ffdd0.png align="center")
    
3. **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
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678451674974/30e513a6-8cc8-44d5-b03e-cb27ff877bb3.png align="center")
    
    An implementation of a **while** loop is also seen below,
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678451758749/26b20486-b4f9-40b7-a518-5178ccd9ef0d.png align="center")
    
    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
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678453090933/00ebf20d-29c0-4872-912b-8c9101fb5515.png align="center")
    
    An image illustrating arrays in BASH is seen below,
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678453148968/42bbe266-0d64-4f87-934e-fb003d0c6104.png align="center")
    
    **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.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678453271762/1d959746-1b18-40db-8d82-39921d2c3e7e.png align="center")
    
4. **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.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678453592694/0adcbda5-5797-41fc-8907-cb72395abb72.png align="center")
    
    When the readarray command is employed and an array is created, a powerful **for** loop sequence can be constructed as seen below
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678453782016/727058f4-4b07-443d-80f8-22c0d6f99e26.png align="center")
    
    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](https://github.com/WilliamsOchu/Bash_Scripting_Projects)

**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](https://www.udemy.com/course/bash-mastery/)

[Bash for beginners by Microsoft Developer](https://www.youtube.com/playlist?list=PLlrxD0HtieHh9ZhrnEbZKhzk0cetzuX7l)
