Mastering Shell Scripting: Your Ultimate Cheat Sheet for Efficient Automation
Tags: shell, shellscript, programming, linux
Published: 2023-05-31 11:02:15

Bash is a powerful scripting language used in the Linux terminal to automate tasks and perform various operations. Here are some essential commands and concepts to help you get started with Bash scripting.

#### **Creating a script:**

Create a file name whatever you want. But, make sure it ends with `.sh`. Open that file in your favorite text editor and write the first line to begin your shell script journey.

`my_script.sh`

```bash
#! /bin/bash
```

The `#! /bin/bash` line is called the **shebang** or **hashbang**, and it is used to specify the interpreter to be used for executing the script. In this case, `#!/bin/bash` indicates that the script should be interpreted and executed using the Bash shell.

**Running the script:**

Open your terminal and go to the directory where you created the script file. Then run the below command to execute the script

```bash
./my_script.sh
```

At this stage, you won't see any output since we have not written anything other than the **shebang** line. Let's add some fun stuff.

#### Display statements:

You can use the `echo` command to print statements or messages in the terminal. For example:

```bash
echo Hello World
```

You will see `Hello World` in your terminal

**Variables:**

You can assign values to variables in Bash using the assignment operator `(=)`. Variable names are usually uppercase by convention and can contain letters, numbers, and underscores. Here's an example:

```bash
NAME="Shiva"
echo "My name is $NAME"
```

**User input:**

To read user input in Bash, you can use the read command. It prompts you to enter a value and stores it in a variable. For example:

```bash
read -p "Enter your name: " NAME
echo "Hello $NAME, nice to meet you!s"
```

Gives you the following output.

```bash
Enter your name: Shiva
Hello Shiva, nice to meet you!s
```

**Conditional Statements:**

Bash supports various conditional statements to control the flow of your script. Here are a few examples:

**Simple If Statement:**

```bash
if [ "$NAME" == "Shiva" ]
then
  echo "Your name is Shiva"
fi
```

**If Statement with Else:**

```bash
if [ "$NAME" == "Shiva" ]
then
  echo "Your name is Shiva"
else
  echo "Your name is not Shiva"
fi
```

**Else If Statement:**

```bash
if [ "$NAME" == "Shiva" ]
then
  echo "Your name is Shiva"
elif [ "$NAME" == "Jack" ]
then
  echo "Your name is Jack"
else
  echo "Your name is NOT Shiva or Jack"
fi
```

Below is an example of comparing two numbers using `-gt` operator in the shell script

```bash
NUM1=3 
NUM2=5
if [ "$NUM1" -gt "$NUM2" ] 
then 
    echo "$NUM1 is greater than $NUM2"
else 
    echo "$NUM1 is less than $NUM2"
fi
```

You can use any of the following operators to do comparisons in a shell script.

* **Equal to**: `==` or `=`
    
    * Example: `[ "$var1" == "$var2" ]`
        
    * Checks if `$var1` is equal to `$var2`.
        
* **Not equal to**: `!=`
    
    * Example: `[ "$var1" != "$var2" ]`
        
    * Checks if `$var1` is not equal to `$var2`.
        
* **Greater than**: `>`
    
    * Example: `[ "$var1" -gt "$var2" ]`
        
    * Checks if `$var1` is greater than `$var2`.
        
* **Greater than or equal to**: `-ge`
    
    * Example: `[ "$var1" -ge "$var2" ]`
        
    * Checks if `$var1` is greater than or equal to `$var2`.
        
* **Less than**: `<`
    
    * Example: `[ "$var1" -lt "$var2" ]`
        
    * Checks if `$var1` is less than `$var2`.
        
* **Less than or equal to**: `-le`
    
    * Example: `[ "$var1" -le "$var2" ]`
        
    * Checks if `$var1` is less than or equal to `$var2`.
        

Following is the example to check whether a file exists with the given or not

```bash
FILE="test.txt"
if [ -e "$FILE" ]
then
  echo "$FILE exists"
else
  echo "$FILE does not exist"
fi
```

**Case Statement:**

The case statement allows you to evaluate the value of a variable against multiple patterns and execute different blocks of code based on the matching pattern.

Following is the example code snippet.

```bash
read -p "Are you 21 or over? Y/N " ANSWER
case "$ANSWER" in
    [yY] | [yY][eE][sS])
        echo "You can have a beer :)"
        ;;
    [nN] | [nN][oO])
        echo "Sorry, no drinking"
        ;;
    *)
        echo "Please enter y/yes or n/no"
        ;;
esac
```

The above code produces the following output.

```bash
# Example 1
Are you 21 or over? Y/N y
You can have a beer :)
# Example 2
Are you 21 or over? Y/N N
Sorry, no drinking
```

**Simple for loop**

The for loop allows you to iterate over a list of values and perform a set of actions for each value.

```bash
NAMES="Brad Kevin Alice Mark"
for NAME in $NAMES
do
    echo "Hello $NAME"
done
```

Following is the output of the above code.

```bash
Hello Brad
Hello Kevin
Hello Alice
Hello MarkWhile loop
```

A while loop in a shell script allows you to repeatedly execute a block of code as long as a certain condition is true. Here is an example of for loop.

```bash
LINE=1
while read -r CURRENT_LINE
do
    echo "$LINE: $CURRENT_LINE"
    ((LINE++))
done < "./contents.txt"
```

**Functions:**

In shell scripting, you can define and use functions to encapsulate a block of code that can be executed multiple times throughout your script.

```bash
sayHello() {
    echo "Hello World"
}

# Call the function
sayHello
```

**Function with parameters:**

```bash
greet() {
    echo "Hello, I am $1 and I am $2 years old"
}

# Call the function and pass arguments
greet "Shiva" "26"
FUNCTION WITH PARAMS
```

**Create a folder and write to a file**

```bash
mkdir hello
touch "hello/world.txt"
echo "Hello World" >> "hello/world.txt"
echo "Created hello/world.txt"
```

Ok. In conclusion, this article covers basic shell scripting concepts anyone can begin with.