Skip to content
DBDeependra Bhatta~/notes
Linux#devops · #technology · #linux · #docker · #ubuntu · #bash-scripting · #foe · #for · #loops · #programming · #shell-scripting · #simple-script · #while

Shell Scripting

It is a way to automate tasks by writing a series of commands in a text file called script that Linux shell can execute. It’s like creating a ‘to do list’ for your computer to follow step by step…

· updated · 5 min read
ON THIS PAGE

It is a way to automate tasks by writing a series of commands in a text file called script that Linux shell can execute. It’s like creating a ‘to do list’ for your computer to follow step by step.

Why?
1.It saves time by automating tasks.
2.Can combine multiple commands like grep, sed, awk etc to automate tasks
3.Works on almost all linux systems.

Writing our first script

SHBash
#!/bin/bash
echo "This is my first script"
  • #! is shebang
  • /bin/bash: we are telling linux to use /bin/bash shell

Variable

  • To create a variable that will cover wide scope for current user we need to create the variable inside .bashrc file which is created when user is created.
    • vim .bashrc path for this file is /home/username. This showuld be written in key value format.
      • Example: export name = dipendra
  • To create variable for all user we need to create variable inside /etc/profile
    • sudo vim /etc/profile
    • Example: export name = dipendra

To take input from user we use

  • read -p “Prompt” variable_name
  • read -ps “Prompt” variable_name #In this case we will not see what user is typing

Positional Argument

  • $0 : To see script path
  • $1: First place argument
  • $2: Second place argument
  • $a: List all the argument that are passsd
  • $#: Count and print no of arguments passed
  • $HOSTNAME: Print hostname of the system
  • $USER: Print currently logged on user
  • $LINENO: Print line number of the script
  • sleep 5s: Wait/sleep for 5 seconds
  • $SECONDS: Print time taken to run all the scripts
  • echo date: Print the date
  • $?: Exit code of the last command

Command substitute

This is the powerful feature of linux shells that enables you to execute a command and substitute its output in place of the command itself. Example is shown below:

SHBash
#!/bin/bash
#To use command subtitute: the command should #be written in `in quotes ` or we can also write command using $
ipadd=`ip -4 addr show`
echo $ipadd
 
ip=$(hostname -I | awk -F " " '{print $1}')
echo $ip
 
disk=`df -h`
echo $disk
 
diskusage=`du -sh *`
echo $diskusage
 
apachestatus=`cat /var/log/dpkg.log | grep apache2-data`
sleep 5s
echo $apachestatus

If

  • -lt = less than
  • -eq = equals to
  • -gt = greater than
  • -f = checks for availabilty

Example1: To print input number is grater than 5 or not

SHBash
#!/bin/bash
read -p "Please enter a numnber that you want to check :" A
if [ $A -eq 5 ]; then
	echo "$A is equals to 5"
elif [ $A -lt 5 ]; then
	echo "$A is less than 5"
else
	echo "$A is greater than 5"
fi

Example 2: To install packages by Checking PID whether it is present or not

SHBash
#!/bin/bash
set -x           #To see step by step what is happening
set -e            #Exit whenever script runs into a problem
sudo apt purge apache2 -y
sudo apt autoremove -y
if [ -f /var/run/apache2/apache2.pid ];then
#-f is to check the availability of the file
   echo "Already installed"
else
   echo "Not installed"
   sudo apt install -y apache2
   sudo systemctl start apache2
   sudo systemctl enable apache2
fi
  • Important things to notice using if:
    • if condition should be like this if [ $A -eq 5 ]; then [space condition space] here before writing condition in [ ] space is mandatory at start and end of the bracket.
    • should be always closed using fi

For

Used when we know the iteration value

Example1: To install multiple packages

SHBash
#!/bin/sh
 
set -e
pkgs="wget curl git apache2"
for x in $pkgs
do                                     #Open
	echo "Installing package $x"
	sudo apt update
	sleep 3s
done                                  #closing loop

Example1: To add multiple users

SHBash
#!/bin/bash
set -e
for x in ram shyam hari
do
	echo "Adding user $x"
	sudo useradd $x
	id $x
	sleep 4s
done

While

We use while loop when we don’t know the iteration value.’

Example 1: To print from 0 to 5

SHBash
#!/bin/bash
counter=0
while [ $counter -lt 5 ]
do
	echo "The value of counter is $counter"
	counter=$((counter+1)) #For arithmetic operation we         should use (())
	sleep 2s
done
echo "We are outside the while loop"

Writing script to terminate the EC2 instances

write a shell script that programmatically launches 100 EC2 instances in parallel and automatically terminates them after 5 minutes?

SHBash
#!/bin/bash
 
# LAUNCH 100 EC2 instances
INSTANCE_IDS=$(aws ec2 run-instances \
    --image-id ami-0abcd1234567890 \
    --count 100 \
    --instance-type t2.micro \
    --key-name MyKeyPair \
    --security-groups MySecurityGroup \
    --query 'Instances[*].InstanceId' \
    --output text)
 
echo "Launched instances: $INSTANCE_IDS"
 
# Wait for 5 minutes
sleep 300
 
# Terminate all instances
aws ec2 terminate-instances --instance-ids $INSTANCE_IDS
 
echo "Terminated instances after 5 minutes."
  • Linux Commands

    To see Ip address of the machine ip addr show :Shows all the interfaces ip ip -4 addr show: Show only ipv4 address ifconfig: Same as ip addr show but it needs net tools to show ip address. Systemctl…

  • Apache web server

    The Apache HTTP server, commonly known as Apache is a free and open-source web server, that delivers web content through the internet. As open-source software, its original source code is freely…

  • Linux commands[2]

    Linux Links Soft links Aka Symbolic link It is a pointer to the original file Just like a shortcut in windows and smaller file size Different inode number If we delete the original file, the soft…