Shell Scripting: A Beginners Guide

Shell Scripting: A Beginners Guide

·

5 min read

I have read numerous documentation and tutorials to help you understand the basics of shell scripting.

A bash script is a series of commands written in a file. By the end of this tutorial, you will be able to write your own bash scripts.

Head over to the terminal, create a new file with the “.sh” extension, and open the file in VS code or vim.

touch myscript.sh

Find your path to your bash shell. Write the below command in your terminal..

which $SHELL

You will get your bash shell path which in my case is /usr/bin/bash.

Let’s get started with a simple bash script that prints “Hello World”.

Write the command in the .sh file. The command looks like this:

#/usr/bin/bash
echo "Hello World"

Modify the file permissions and make it executable by using the command below:

chmod +x myscript.sh

Run the script:

./myscript.sh

You will get the output “Hello World”. Congrats you successfully ran your first bash script.

Next, we will look at how to declare and use variables. In bash scripting, there is a convention to use capital letters when declaring with variables.

NAME="Ashu"

The variable can be printed in the shell in the following ways:

echo "My name is $NAME"
echo "My name is ${NAME}"

Again run the script.

./myscript.sh

To comment a line, we use #.

# This is a comment

Next we will see how to take inputs from the user. Use the below commands:

read -p "Enter your name: " NAME
echo "Hello $NAME"

Here we read the variable NAME from the user and echo it to the terminal.

IF Condition

if [ "$NAME" == "Ashu" ]
then
     echo "Your name is Ashu"
fi

Spaces and brackets should be used properly here. Also, notice that we end the command with the reverse of “if” that is, “fi”.

If Else Condition

if [ "$NAME" == "Ashu" ]
then
    echo "Your name is Ashu"
else
    echo "Your name is not Ashu"
fi

Else If

“elif” keyword is used to declare else if conditions.

if [ "$NAME" == "Ashu" ]
then
    echo "Your name is Ashu"
elif [ "$NAME" == "Jack" ]
then
    echo "Your Name is Jack"
else
    echo "Your name is not Ashu or Jack"
fi

Comparison Operators

We have the following comparison operators in bash scripting:

  1. eq - equal to

  2. ne - not equal to

  3. gt - greater than

  4. ge - greater than or equal to

  5. lt - lower than

  6. le - lower than or equal to

Here is the implementation of comparison operators.

NUM1=3
NUM2=5

if [ $NUM1 -gt $NUM2 ]
then
    echo "num1 is greator than num2"
else
    echo "num1 is smaller than num2"
fi

In the above code, we use -gt to check if NUM1 is greater than NUM2.

FILE CONDITIONS

We have the following file conditions:

  1. -d is a directory

  2. -f is a file

  3. -e file or directory exists

  4. -g if group id is set on a file

  5. -r file is readable

  6. -u if the user id is set on a file

  7. -w file is writable

The below code checks if the string selected is a file.

FILE="test.txt"
if [ -f "$FILE" ]
then 
    echo "$FILE is a File"
else
    echo "$FILE is not a File"
fi

CASE STATEMENT

If you are coming from a different programming language, you already might be aware of switch-case statements which are alternative ways of If-Else statements.

Here is the syntax of switch case in bash:

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

The syntax might be intimidating at first but it is how it is. We take input ANSWER and check if it is yes or no. We also create a default case and then end with the reverse of the case statement, “esac”.

Using For Loops in Bash

Below is the syntax for using loops:

NAMES="brad Alice Kelvin Ashu"
for NAME in $NAMES
    do 
        echo "Hello $NAME"
done

Here we take multiple names in a string and then loop and print them. Notice that we end the command using the “done” keyword.

If you are familiar with any other programming language, you might already be comfortable reading here.

Now we are going to do exciting stuff with bash scripts. Let us try renaming files using for loops.

Start by creating multiple files.

touch a.txt
touch b.txt
touch c.txt
FILES=$(ls *.txt)
NEW="new"

for FILE in $FILES
    do
        echo "Renaming $FILE to new-$FILE"
        mv $FILE $NEW-$FILE
done

“ls” command will list all files in the directory and mv will rename the files. For example, a.txt will be renamed to new-a.txt.

Using while loop to read file line by line

LINE=1
while read -r CURRENT_LINE
    do
        echo "$LINE - $CURRENT_LINE"
        ((LINE++))
done < "./new-a.txt"

Here we initialize the variable LINE as 1 and increment it on each loop by 1 and print the contents of the file.

Functions

function sayHello() {
    echo "Hello World"
}

sayHello

Functions are implemented in a similar way as in other languages.

Using Functions with parameters

function greet(){
    echo "Hello $1 and $2"
}

greet "Ashu" "Brad"

Create a File and Write it to the File

mkdir hello
touch hello/world.txt
echo "Hello World" >> hello/world.txt
echo "File created hello/world.txt"

mkdir is used to create the directory, and touch is used to create file world.txt. And then, you can use echo to write data to the created file.

Did you find this article valuable?

Support Ashutosh by becoming a sponsor. Any amount is appreciated!