Sitemap
Samuel Orji

Samuel Orji

Cloud support | Technical writing | Cybersecurity • Super Flexible - Open to roles.

Bash scripting

In this personal project, I practiced hands-on bash scripting for automating tasks on Linux machines.

8 min readAug 5, 2026

--

The Bourne-Again Shell (Bash) logo on gray BG
Bash logo

Introduction

Bash scripting is the process of writing a sequence of commands in a text file to automate repetitive tasks on Unix-like operating systems.

Instead of typing commands manually into a terminal, it is saved into a reusable script file (.sh) to save time and reduce errors.

Objectives

  • Create and run a simple Bash script
  • Apply variables in Bash scripting
  • Pass arguments to Bash scripts
  • Use arrays in Bash
  • Use arithmetic operators in Bash scripts
  • Apply conditional and case statements to Bash scripts
  • Apply loop statements to Bash scripts

Creating a simple Bash script

To do this, I:

  • Made a new directory named scripts to host all bash scripts
  • Moved to the new scripts directory
mkdir scripts
cd scripts
  • Created a new script file named hello.sh using cat so it opens from the terminal automatically:
cat > hello.sh
  • Wrote the following to hello.sh in the blank line that followed:
echo 'Hello Dubem!'
  • Pressed Ctrl D to close hello.sh and return to scripts directory
  • Confirmed it works by running the new script using bash command:
bash hello.sh

Hello Dubem! was displayed on the terminal showing that the script works.

Tried using the universal shell command ./ to run the new script:

./hello.sh

Permission was denied meaning I don’t have execute access for hello.sh. By default, file owners do not have execute access on Linux. The bash command does not need execute access but it only works for bash shell.

Corrected this by adding execute permission for myself using:

chmod u+x hello.sh

Finally, used the ./ command again and Hello Dubem! — it worked.

Note: The ./ command usually follows the shell specified by the shebang line. The shebang (#!) line is usually added to the top of a script to help a shell understand the script. This way, bash can interprete a script written for zsh.

Running scripts as a command

At first, the new script could only be run successfully from the scripts directory. To ensure it runs as a command from any location, it has to be added to the PATH variable. To do this, I:

Looked through the contents of the PATH variable using:

echo $PATH

Got the folder path for the scripts directory using:

pwd

Output — /home/dubem/scripts

Added the /home/dubem/scripts path to PATH variable using:

export PATH=$PATH:/home/dubem/scripts

Confimed that I can now run hello.sh script as a command without bash or ./ from any location. It worked!!!

I can now run hello.sh script as a command without bash or ./ from any location.
Success!

Using variables in bash scripting

To practice this I:

  • Opened hello.sh for editing on nano text editor
nano hello.sh
  • Added a line that asks a question about daily goals
  • Entered next line to prompt the user to fill in the goals variable
  • Added a final line to respond and apply the goals variable
echo "What are your goals today"
read goals
echo "Goodluck with $goals"
  • Returned to the terminal and ran hello.sh to confirm
  • Entered my goal for the day in the prompt and tapped Enter

Output shows that the variable works perfectly.

The modified hello.sh command works
Success!

Note:
The
read command is the most realistic way to work with variables.
Sentences containing variables must be flanked by a double quote “” and the dollar sign $ used to indicate a variable.
Variables can be integers, strings, or characters.

Commands as variables

Commands that change over time also function as variables. Such as whoami and date commands. whoami returns the username while date returns date, time, and timezone.

tested whoami and date commands

To practice applying these commands as variables, I:

  • Edited the first and second line of the hello.sh script to add them
echo "Hello, $(whoami)"
echo "What are your goals today $(date)"
  • Saved it and returned to the terminal to run hello.sh again

Output shows it worked:

success!

Note:
A command must be enclosed in parenthesis () to run properly as a variable.

Constant variables

These variables cannot be changed and are created using the readonly command. Example:

readonly pi=3.142
as expected, trying to change pi returned warning that pi is a readonly variable

As expected, trying to change the value of pi returned a warning that pi is a readonly variable.

Passing arguments to Bash scripts

To practice this, I:

  • Created a new script named count_lines.sh
cat > count_lines.sh
#!/bin/bash

echo -n "Please enter a filename: "
read filename
nlines=$(wc -l < $filename)
echo "There are $nlines lines in $filename"
  • Ran the script and entered hello.sh as the filename when prompted
  • Confirmed that the script works:
Ran the script and entered hello.sh as the filename when prompted and confirmed that it works
  • Edited the script using nano so that filenames can be passed as part of the command line argument on the terminal. With nano, I:
  • Removed the two command lines following the shebang line
  • Added $1 as the new variable to replace $filename on the last two lines and exited nano.
#!/bin/bash

nlines=$(wc -l < $1)
echo "There are $nlines lines in $1"
  • Confirmed this by running the command and it worked:
count_lines.sh hello.sh
It worked. I did not have to fill in any filename this time.
Success! I did not have to fill in any filename this time.

Note:
$1 is a positional parameter that passes the second element in a command line argument to the specified script.

Passing multiple arguments to a bash script

To achieve this, I:

  • Edited the count_lines.sh script to accept up to three arguments
#!/bin/bash

n1=$(wc -l < $1)
n2=$(wc -l < $2)
n3=$(wc -l < $3)

echo "There are $n1 lines in $1"
echo "There are $n2 lines in $2"
echo "There are $n3 lines in $3"
  • Confirmed that it worked:
Press enter or click to view image in full size
Edited the script to be able to accept three arguments and count the lines of three files.
Success! I counted the lines of three files.

Using arrays in Bash scripts

To practice using arrays, I:

  • Opened the hello.sh script on nano
  • Decided to list some items that I need to reach my goal
  • Listed the items in an array instead of doing it line by line
  • Added an echo line to print the array items
  • Added a echo line in between to help the narrative

items=("pc" "internet_access" "power_source")

echo 'These are the items needed to achieve your goals'

echo ${items[*]}

Confirmed that it works:

Successfull added an array line to my script and it worked well on the terminal.
Success! The script still works.

Note:
Array elements can be omitted. To omit the second element in an array on the terminal, apply the unset num[1] command in the script after the array line. Counting usually starts from 0.
Different data types can be added to an array.

Using arithmetic operators in Bash scripting

First I practiced using addition to add up the filesize of two files:

  • Created a file named addition.sh using cat
  • Wrote the following into it:
#!/bin/bash

fs1=$(du -b $1 | cut -f1)
fs2=$(du -b $2 | cut -f1)

echo "File size of $1 is: $fs1"
echo "File size of $2 is: $fs2"

total=$(($fs1 + $fs2))

echo "Total size is: $total"

Note:
du -b called the filesize and filename of the files. pipe(|) redirected the outputs to cut -f1 which removed the filenames leaving just the filesizes (fs1, fs2). The fifth line holds the actual addition command.

Get Samuel Orji’s stories in your inbox

Join Medium for free to get updates from this writer.

Confirmed that it works:

Running the addition.sh script returned the total of two filesizes
Success!

Other arithmetic operators

Subtraction: -

Multiplication: *

Division: /

Power: **

Conditional and case statements in Bash scripts

To practice this gradually, I:

Edited my hello.sh script to add an if statement in 3rd and 4th lines

#! /bin/bash

echo "Hello, $(whoami)"

if [ $(whoami) = 'root' ]; then
echo "You are root"
fi

echo "What are your goals today $(date)"

read goals

items=("pc" "internet_access" "power_source")

echo 'These are the items needed to achieve your goals'

echo ${items[*]}

echo "Goodluck with $goals"

Confirmed that it works by running the script as root user (sudo):

sudo ./hello.sh

Output:

Second line shows that the if statement worked
Second line of the output shows that the if statement worked

P. S: I changed the colour of my command terminal from here.

Applied else condition by adding it after the if statement in the script

else
echo "You are not root"

Confirmed that it works by running hello.sh without root priviledges

Output:

Confirmed the else statement works by not using sudo
  • Practiced using elif statements by replacing the former if/else statement with a statement that accommodates elif.
  • Added a few other lines to improve the script
echo 'How old are you?'

read age

if [ $age -lt 13 ]; then
echo "You are a kid."
elif [ $age -lt 20 ]; then
echo "You are a teenager."
elif [ $age -lt 65 ]; then
echo "You are an adult."
else
echo "You are an elder."
fi

Confirmed that it works by running hello.sh

Output:

The just added conditional statement that includes the elif condition worked perfectly.
Success!

Note:
There can be many elif conditions but only one else condition in an if statement.
A statement containing if, elif, and else conditions can be written on a single line but must be seperated by semi-colons.
If statements can also be nested under another if statement like this:

if [ $TEMP -gt 5 ]; then
if [ $TEMP -lt 15 ]; then
echo "The weather is cold."
elif [ $TEMP -lt 25 ]; then
echo "The weather is nice."
else
echo "The weather is hot."
fi
else
echo "It's freezing outside ..."
fi

Loop statements in Bash scripts

To practice the for loop, I:

Replaced the echo ${items[*]} line with a for statement in hello.sh script

items=("pc" "internet_access" "power_source")

echo 'These are the items needed to achieve your goals'

for i in ${items[@]};do
echo $i
done

This made a slight change to the output after running hello.sh:

The content of items array are listed one on a line instead of on the same line as the former echo ${items[*]} command. Much better!

The content of items array are now listed one on a line instead of all on the same line as the former echo ${items[*]} command. Much better!

To practice while loop and break, I:

Added a while statement with a break command so it stops after one line. I added this after the conditional statement.

while [ $age -le 26 ];do
echo "Vibrant Gen-Z."
break
done

Confirmed that it worked:

The while statement worked well

Note:
if statements can be nested under loop statements.
break or continue can follow after. break ends a loop and continue extends it.
The
until loop contradicts the while loop but statements have same structure.

Functions in Bash

I learnt that a function is a less tedious way of repeating commands within a script. A function is defined, thus:

function_name () {
commands
}

To repeat the commands listed under a function, all that is needed is the function_name.

Conclusion

Through this project, I successfully practiced bash scripting and applied several modifications that help bash scripts handle task automation.

--

Samuel Orji
Samuel Orji

Written by Samuel Orji

Cloud support | Technical writing | Cybersecurity • Super Flexible - Open to roles.