Shell Script Basics
Introduction
Shell scripting means writing sequence of commands that shell interprets or executes. Shell scripting serves as a backbone for automating repetitive tasks, deploying code, managing infrastructure, and handling complex DevOps workflows. Common scripting languages include: Shell scripts - sh, bash, csh, tcsh, zsh. Here, we will be writing scrips on bash.
To run the script, first you need to change the permission of file to 755.
chmod 755 file_name
After changing permission, you can run script file using following command.
./file_name
A First Script:
Let’s start with the first script.
#!/bin/bash
echo "Hello World"
The first line is called shebang that tells the Unix that this file is executed by ./bin/bash. This is the location of Bourne Shell in system.
The second line runs the command echo which prints the string inside the string i.e. Hello World.
Variables
Just like any other programming languages, variables are the name of the chunk of memory where any data can be stored, read and changed while running the script. In bash, we don’t need to declare the variable with explicit data type.
#Example 1
usr_name="my name"
echo "My name is: $usr_name"
#Example 2
read -p "Enter your name" usr_name
echo "My name is: $usr_name"
#Example 3
read n1
read n2
echo "$((n1+n2))"
In example 1, we assign the value “my name” to the variable name and then the value is printed using echo command.
In example 2, read command is used to take input from user along with -p which prompts user to enter name.
In example 3, the sum of two integers is calculated. Shell does not differentiate different data types, so expr command or (( )) is used to perform arithmetic operations.
Conditional Statements
if-else Statement
if-else statement is used in decision making condition based on situations.
n=5 if[$n -gt 0]; then echo "Positive" elif [$n -eq 0]; then echo "Zero" else echo "Negative" fi
Case Statement
This is similar to switch-case statement in other languages. Case statement is suitable for handling multiple conditions.
choice=1
case $choice in
1) echo "Number is 1";;
2) echo "Number is 2";;
*) echo "Invalid";;
esac
Loops
For Loop
For loops iterate through a list of items.
for((i=0;i<=5;i++))do echo "Iteration: $i)) done
While Loop
While loops repeat set of statements as long as the condition is true.
n=1 while [ n -lt 5 ]; do echo "Iteration $n" ((n++) done
Until Loop
Until loop is opposite of while. lt repeats set of statements as long as the condition is false.
n=1 until [ n -gt 5 ]; do echo "Iteration $n" ((n++)) done
Functions
Functions allow you to group commands into a named block of code that can be reused throughout the script. Functions make scripts modular and reduce code duplication.
#FUnction Definition
sayHello(){
echo "Hello $1"
}
#Calling Function
sayHello "abc"
sayHello "xyz"
Functions may return a value after completing its execution. In shell scripting, there are two common ways to get output from a function:
Exit Command: Terminate the entire script and return a status code.
Return Command: Returns the integer value between 0 and 255 from the function.
#Function using return command
isEven(){
if (( $1 % 2 == 0 )); then
return 1
else
return 0
fi
}
#Function using exit command
isEven2(){
if (( $1 % 2 == 0 )); then
exit 1
fi
}
#Function Calling
isEven 3
if [ $? -eq 1 ]; then
echo "odd number"
else
echo "even number"
fi
isEven2 3
Error Handling
There is not dedicated error handling methods in shell scripting like try …. catch functions in other programming languages. However, we can achieve similar functionality using if….then statement in shell.
#Function to create direcctory
create_directory(){
mkdir demo
}
#Error handling, if any error occurs while runnig function, the statements inside if statement will execute
if ! createdirectory; then
echo "Directory already exists"
exit 1
fi
We can used various flags(options) for robust error handling:
set -e
This command prevents script from running after an error and exit immediately.
set -u
This causes the script to throw an error and exit if it encounters any undefined variables.
set -o pipefail
This ensures that a pipeline turns a failure status if any command in the pipeline fails.
Mini Project
In this project, we will be writing script to automate the process of launching EC2 instance using AWS CLI. Follow the following steps to do this project.
To access AWS from CLI, AWS CLI needs to be installed and configured. To check if AWS CLI is installed:
check_awscli(){ if ! command -v aws &> /dev/null; then echo "AWS CLI not found" return 1 fi }
If AWS CLI is not installed in your system, following script installs AWS CLI V2 and configure AWS CLI. You will be asked to provided necessary details to configure AWS CLI.
install_awscli(){ echo "Installing AWS CLI" # Download and install AWS CLI v2 sudo apt-get install -y unzip &> /dev/null curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install # Verify installation aws --version # Clean up rm -rf awscliv2.zip ./aws #configure aws cli after installation aws configure }
Then, the following script creates the instance on AWS based on the details provided by the user.
create_ec2_instance() { local ami_id="$1" local instance_type="$2" local key_name="$3" local subnet_id="$4" local security_group_ids="$5" local instance_name="$6" # Run AWS CLI command to create EC2 instance instance_id=$(aws ec2 run-instances \ --image-id "$ami_id" \ --instance-type "$instance_type" \ --key-name "$key_name" \ --subnet-id "$subnet_id" \ --security-group-ids "$security_group_ids" \ --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$instance_name}]" \ --query 'Instances[0].InstanceId' \ --output text ) if [[ -z "$instance_id" ]]; then echo "Failed to create EC2 instance" >&2 exit 1 fi echo "EC2 instance $instance_id created successfully" }
We will call all the above mentioned functions in main function. Main function also reads the necessary details like Image ID, Instance type, Key name, Subnet ID, Security groups ID, and Instance name to be created.
main(){ if ! check_awscli; then install_awscli fi read -p "Enter AMI ID: " ami_id read -p "Enter Instance Type: " instance_type read -p "Enter Key Name: " key_name read -p "Enter Subnet ID: " subnet_id read -p "Enter Security Groups ID: " security_groups read -p "Instance Name: " instance_name if ! create_ec2_instance "$ami_id" "$instance_type" "$key_name" "$subnet_id" "$security_groups" "$instance_name"; then echo "Failed to create EC2 instance" exit 1 fi echo "Wait few seconds to get instance in running state..." }
Finally add the following script to call the main function.
main "$@"
Congratulations, You have successfully learnt basics of shell scripting with an amazing project.
Subscribe to my newsletter
Read articles from Binod Prasad Joshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by