Bash Scripting : A Beginner's Guide

I'm building systems across industries, ensuring seamless software delivery. I manage everything from system design to deployment, driving operational excellence and client satisfaction.
Bash scripting is a powerful way to automate tasks in Unix-based operating systems. This guide will cover the essentials of Bash scripting, including how to use comments, the echo and read commands, built-in variables, and how to handle script arguments. Additionally, we'll provide an example script to list all files and directory sizes in the current path.
Comments
Comments are essential for adding explanations or annotations to your script, making it easier to understand and maintain.
Single Line Comments
Single-line comments begin with the # symbol.
#!/bin/bash
# This is a single-line comment
Multi Line Comments
We can have Multiline comment by adding ": << nameOfComment" at start of first line and to End it, we need to add "nameOfComment" to end of last line of comment
#!/bin/bash
: << EOF
This is a multi-line comment.
It can span multiple lines.
All the text between the EOF markers is ignored.
EOF
Displaying Messages: echo
The echo command is used to display messages on the terminal.
#!/bin/bash
str='Hello World'
echo "$str"
Reading User Input: read
The read command is used to take input from the user at runtime.
#!/bin/bash
echo "Enter 1st Num"
read firstNum
echo "Enter 2nd Num"
read secondNum
sum=$((firstNum + secondNum))
echo "Sum is $sum"
Using Built-in Variables
Bash has several built-in variables that can be used in scripts, such as PWD for the current directory and USER for the current user.
#!/bin/bash
echo "Current Directory: $PWD"
echo "Current User: $USER"
Taking Arguments in Scripts
You can pass arguments to a script while running it and access them using $1, $2, etc.
#!/bin/bash
# index.sh /home/ubuntu txt
dir=$1 # dir value will become /home/ubuntu
extn=$2 # extn value will become txt
ls "$dir"/*."$extn"
Example Script: List Files and Directory Sizes
This script lists all files and directories in the current path along with their sizes.
#!/bin/bash
list_file_and_directory() {
echo "Files and Directories in current Path"
for item in *; do
if [ -f "$item" ]; then
size=$(ls -l "$item" | awk '{print $5}')
echo "- $item ($size KB)"
elif [ -d "$item" ]; then
size=$(du -sh "$item" | awk '{print $1}')
echo "- $item ($size)"
fi
done
echo "..."
}
list_file_and_directory
Bash scripting is a versatile tool that can help you automate a wide range of tasks. By understanding the basics, such as comments, echo, read, built-in variables, and handling arguments, you can create powerful scripts to simplify your workflow. Happy scripting!
