Bash scripting
In this personal project, I practiced hands-on bash scripting for automating tasks on Linux machines.
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.shHello Dubem! was displayed on the terminal showing that the script works.
Tried using the universal shell command ./ to run the new script:
./hello.shPermission 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.shFinally, 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 $PATHGot the folder path for the scripts directory using:
pwdOutput — /home/dubem/scripts
Added the /home/dubem/scripts path to PATH variable using:
export PATH=$PATH:/home/dubem/scriptsConfimed that I can now run hello.sh script as a command without bash or ./ from any location. It worked!!!
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.
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.
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:
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.142As 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:
- 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.shNote:
$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:
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:
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:
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.shOutput:
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:
- 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."
fiConfirmed that it works by running hello.sh
Output:
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 ..."
fiLoop 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
doneThis made a slight change to the output after running hello.sh:
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
doneConfirmed that it worked:
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.



