Unleashing the Power of Shell Scripting
I had explained about Unix/Linux and their commands in my previous posts —
Let’s discover the world of shell and shell scripting in this post.
What is Shell?
Shell is a command line interpreter. It is an interface between user and kernel. Shell provides users with an interface and accepts human-readable commands into the system and executes those commands which can run automatically and give the program’s output in a shell script.
An Operating is made of many components, but its two prime components are
- Kernel
- Shell
Types of Shell
There are two main shells in Linux:
1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:
- POSIX shell also is known as sh
- Korn Shell also knew as sh
- Bourne Again SHell also knew as bash (most popular)
2. The C shell: The prompt for this shell is %, and its subcategories are:
- C shell also is known as csh
- Tops C shell also is known as tcsh
Shell Scripting
Shell Scripting is an open-source computer program designed to be run by the Unix/Linux shell. Shell Scripting is a program to write a series of commands for the shell to execute. It can combine lengthy and repetitive sequences of commands into a single and simple script that can be stored and executed anytime which, reduces programming efforts.
- /bin/bash and /bin/sh is interactive shell
- /sbin/nologin shell is non-interactive shell
A shell script has syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. It would be very easy to get started with it.
A shell script comprises the following elements –
- Shell Keywords — if, else, break etc.
- Shell commands — cd, ls, echo, pwd, touch etc.
- Functions
- Control flow — if..then..else, case and shell loops etc.
Why do we need shell scripts?
There are many reasons to write shell scripts:
- To avoid repetitive work and automation
- System admins use shell scripting for routine backups.
- System monitoring
- Adding new functionality to the shell etc.
Some Advantages of shell scripts
- The command and syntax are exactly the same as those directly entered in the command line, so programmers do not need to switch to entirely different syntax
- Writing shell scripts are much quicker
- Quick start
- Interactive debugging etc.
Some Disadvantages of shell scripts
- Prone to costly errors, a single mistake can change the command which might be harmful.
- Slow execution speed
- Design flaws within the language syntax or implementation
- Not well suited for large and complex task
- Provide minimal data structure unlike other scripting languages. etc.
How to determine Shell
You can get the name of your shell prompt, with following command :
$ echo $SHELLThe $ sign stands for a shell variable, echo will return the text whatever you typed in.
Let’s write our first script
#!/bin/bash
echo "My First Script!"To run it,
$ chmod +x script.sh
$ ./script.shShebang
You might have noticed in above script that it starts with #!/bin/bash This is called shebang. It is basically to refer the path to the interpreter. There are many interpreters, some of them are: bash, zsh, csh and ksh, etc.
All the best people in life seem to like LINUX. — Steve Wozniak
To use bash: #!/bin/bash
To use zsh: #!/bin/zsh
To use ksh: #!/bin/ksh
To use csh: #!/bin/csh
Why Shebang?# is often called sharp and ! is called Bang, hence the name sharp bang, but generally people say it shebang instead of sharp bang.
Note* If a script does not contain the shebang, the commands are executed using your shell, so there are chances that the code might run properly, but still, that isn’t the correct way of doing it!
Comments
Comments are started by a # sign, anything after pound sign on that line is ignored.
Operations
In shell scripting, to perform arithmetic operations we need to use double parenthesis (( )) which is used for arithmetic expansion on integers. The double parenthesis (( )) is also called a unary operator.
#!/bin/bashn1=10
n2=5echo "Sum of two numbers: "$(($n1+$n2)) # Addition
echo "Sub of two numbers: "$(($n1-$n2)) # Substraction
echo "Mul of two numbers: "$(($n1*$n2)) # Mulitplication
echo "Div of two numbers: "$(($n1/$n2)) # Division
echo "Modulus of two numbers: "$(($n1%$n2)) # ModulusWe can also use test command to work with arithmetic and string operations which provide more flexibility along with unary operators.
OPERATORS:
- Arhmetic operators
2. Relational operators
Get Dhanush Vasudevaraju’s stories in your inbox
Join Medium for free to get updates from this writer.
a.Numeric comparision operators
b.String comparision operators
3. Logical operators
Conditionals
In shell scripting, [[ ]] or test command can be used for evaluating conditional expressions. Below are certain unary operators that can be used for testing the conditions
Conditions
[[ -z STRING ]]- Empty string[[ -n STRING ]]- Not empty string[[ STRING == STRING ]]- Equal[[ STRING != STRING ]]- Not equal[[ NUM -eq NUM ]]- Equal[[ NUM -ne NUM ]]- Not equal[[ NUM -lt NUM ]]- Less than[[ NUM -le NUM ]]- Less than or equal[[ NUM -gt NUM ]]- Greater than[[ NUM -ge NUM ]]- Greater than or equal[[ ! EXPR ]]- Not[[ X && Y ]]- And[[ X || Y ]]- Or
File Conditions
[[ -e FILE ]]- Exists[[ -r FILE ]]- Readable[[ -h FILE ]]- Symbolic link[[ -d FILE ]]- Directory[[ -w FILE ]]- Writable file[[ -s FILE ]]- File size is > 0 bytes[[ -f FILE ]]- File[[ -x FILE ]]- Executable file
#!/bin/basha=10
b=20
# less than using square brackets
if [[ $a -lt $b ]]
then
echo "a is less than b"
else
echo "a is not less than b"
fi
# less than using test command
if test "$a" -lt "$b"
then
echo "a is less than b"
else
echo "a is not less than b"
fiLoops
if else
if else loop is a conditional statement that allows executing different commands based on the condition true/false. Here square brackets [[ ]] are used to evaluate a condition.
Let’s create a file named ifelse.sh and input the below code
#!/bin/bash# -e stands for exists
if [[ -e ./ifelse.sh ]]
then
echo "File exists"
else
echo "File does not exist"
fielif
elif is a combination of both else and if. It is used to create multiple conditional statements and it must be always used in conjunction with if else statement
#!/bin/bashread -p "Enter the number between 1 to 3: " number
if [[ $number -eq 1 ]]
then
echo "The number entered is 1"
elif [[ $number -eq 2 ]]
then
echo "The number entered is 2"
elif [[ $number -eq 3 ]]
then
echo "The number entered is 3"
else
echo "Invalid Number"
fifor
The for loop is used to iterate over a sequence of values and below is the syntax
#!/bin/bashfor i in {1..10}
do
echo "Val: $i"
done
# C style/Old Style of for loop
for((i=0;i<=10;i++))
do
echo "Val: $i"
donewhile
The while loop is used to execute a set of commands repeatedly as long as a certain condition is true. The loop continues until the condition is false.
#!/bin/bashcount=0
while [ $count -lt 5 ]
do
echo $count
count=$(($count+1))
doneuntil
The until loop in shell scripting is used to execute a block of code repeatedly until a certain condition is met.
#!/bin/bashcount=1
until [ $count -gt 5 ]
do
echo $count
count=$(($count+1))
doneBreak Statement
break is a keyword. It is a control statement that is used to exit out of a loop ( for, while, or until) when a certain condition is met. It means that the control of the program is transferred outside the loop and resumes with the next set of lines in the script
#!/bin/bashcount=1
while true
do
echo "Count is $count"
count=$(($count+1))
if [ $count -gt 5 ]; then
echo "Break statement reached"
break
fi
doneContinue statement
continue is a keyword that is used inside loops (such as for, while, and until) to skip the current iteration of the loop and move on to the next iteration. It means that when the continue keyword is encountered while executing a loop the next set of lines in that loop will not be executed and moves to the next iteration.
#!/bin/bashfor i in {1..10}
do
if [ $i -eq 5 ]
then
continue
fi
echo $i
doneFunctions
Functions are a block of code which can be used again and again for doing a specific task thus providing code reusability.
Normal Function
#!/bin/bashsum(){
echo "The numbers are: $n1 $n2"
sum_val=$(($n1+$n2))
echo "Sum: $sum_val"
}
n1=$1
n2=$2
sumFunction with return values
To access the return value of the function we need to use $? to access that value
#!/bin/bashsum(){
echo "The numbers are: $n1 $n2"
sum_val=$(($n1+$n2))
echo "Sum: $sum_val"
return $sum_val
}
n1=$1
n2=$2
sum
echo "Retuned value from function is $?"Variables
The variable is a placeholder for saving a value which can be later accessed using that name. There are two types of variable
Global- Variable defined outside a function which can be accessed throughout the scriptLocal- Variable defined inside a function and can be accessed only within it
#!/bin/bash# x & y are global variables
x=10
y=20
sum(){
sum=$(($x+$y))
echo "Global Variable Addition: $sum"
}
sum
sub(){
# a & b are local variables
local a=20
local b=10
local sub=$(($a-$b))
echo "Local Variable Substraction: $sub"
}
subArrays
An array is a variable that can hold multiple values under a single name
${arrayVarName[@]}- displays all the values of the array.${#arrayVarName[@]}- displays the lenght of the array.${arrayVarName[0]}- displays the first element of the array${arrayVarName[-1]}- displays the last element of the arrayunset arrayVarName[2]- deletes the 2 element
#!/bin/bash# Declare an array of fruits
fruits=("apple" "banana" "orange" "guava")# Print the entire array
echo "All fruits using @ symbol: ${fruits[@]}"
echo "All fruits using * symbol: ${fruits[*]}"# Print the third element of the array
echo "Third fruit: ${fruits[2]}"Argument Passing
We can pass arguments that can be used inside the scripts when it is executed. Those arguments can be accessed by the script using special variables like $1 $2 $3 etc.
$0- returns the file name of the shell script.$@- returns all arguments passed from cli.$#- returns the no of arguments passed from cli.
Let’s say we have a script file named argument_passing.sh and let's pass 2 arguments to it.
argument_passing.sh "Dhanush" "Software Engineer"#!/bin/bash# gives the filename of the script itself
echo "FileName Argument: "$0 # argument_passing.sh
# gives the first argument passed
echo "First Argument: "$1 # Dhanush
# gives the second argument passed
echo "Second Argument: "$2 # Software Engineer
# displays all arguments passed
echo "All Arguments: "$@ # Dhanush Software Engineer
# displays number of arguments passed
echo "No of Arguments: "$# # 2







