Intro to the amazing world of Shell scripting

Reading Time: 7 minutes

Shell Scripting

A shell script uses the Linux commands to perform a particular task. It provides loop and conditional control structures that repeat Linux commands or make decisions on which commands you want to execute. It will be very easy to learn if you already have some experience in programming (a very basic level will also work fine).

Shell Scripting provides automation, makes repetitive task, system monitoring easier to perform. Its easier to get started with it. System admins use shell scripting for routine backups and various other tasks.

Shell

A shell, by definition, is an interpretive environment within which you execute commands. It 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. When you run the terminal, the Shell issues a command prompt (usually $), where you can type your input,(commands) which is then executed when you hit the Enter key. The output or the result is thereafter displayed on the terminal. Consider the below image on issuing ls command it will list all the items.

Types of Shell

There are different types of shells available for the linux distributions:

  • BASH (Bourne Again SHell) – This is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. You can install it on Windows OS also.
  • CSH (C SHell) – This is a Unix shell created by Bill Joy while he was a graduate student at University of California, Berkeley in the late 1970s. The C shell’s syntax and usage are very similar to the C programming language.
  • KSH (Korn SHell) – KornShell ( ksh ) is a Unix shell which was developed by David Korn at Bell Labs in the early 1980s and announced at USENIX on July 14, 1983. The Korn Shell also was the base for the POSIX Shell standard specifications etc.

You can get the name of your shell prompt by the command

echo $SHELL

The $ sign stands for a shell variable, echo will return the text whatever you typed in.

How to write shell script?

You can write shell scripts using text editors. On your Linux system, open a text editor program, open a new file to begin typing a shell script or shell programming, then give the shell permission to execute your shell script .

Let us understand the steps in creating a Shell Script:

  1. Create a file using a vi editor(or any other editor). 
  2. Name the file with the extension .sh .
  3. Start the script with #! /bin/sh (She-bang).
  4. Write some code .
  5. Save the script file.
  6. Make the script executable with command chmod +x <fileName>.sh .
  7. For executing the script type bash <fileName>.sh or ./<fileName>.sh .

Note: Either we can run the script as a command-line argument to bash or we can grant execution permission to the script so it becomes executable.

Shebang

The sign #! is called she-bang and is written at the starting of the script. It passes instruction to program which is mentioned against #!.

To run your script in a certain shell (your system should support that shell), start your script with #! followed by the shell name.

#!/bin/bash  
echo Hi Knolders  
#!/bin/ksh  
echo Hello Knoldus

Variables in shell scripts

Variables store data in the form of characters and numbers. Similarly, Shell variables are used to store information and they can call by the shell only. Below is a small script which will use a variable. Scripting languages usually do not require variable type declaration before its use as they can be assigned directly. Furthermore, there are variables used by the shell environment and the operating environment to store special values, which are called environment variables.

To view all the environment variables related to a terminal, issue the env command. Some of the well-known environment variables are HOME , PWD , USER , UID , SHELL , and so on.

env

For every process, environment variables in its runtime can be viewed by:

cat /proc/$PID/environ
#!/bin/sh
echo "what is your name?"
read name
echo "How do you do, $name?"
read reply
echo "Great to see you."

In the above script you can notice ‘name’ and ‘remark’ are variables which can be used using $<variable_name>.

Let’s execute a shell script

Try to execute the given code in the similar fashion as mentioned above and observe the output. Create a bash file with the name, ‘while_loop.sh’, to know the use of while loop. In this example, while loop will iterate for 10 times. The value of count variable will increment by 1 in each step. When the value of count variable will 10 then the while loop will terminate.

#!/bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 10 ];
then
break
fi
((count++))
done

Run the file.

Arrays and associative arrays

Arrays are a very important component for storing a collection of data as separate entities using indexes. Regular arrays can use only integers as their array index. On the other hand, Bash also supports associative arrays that can take a string as their array index. To use associate arrays, you must have Bash Version 4 or higher.

  1. You can define array in many ways. Define an array using a list of values in a line as follows:

array_var=(1 2 3 4 5 6) #values will be stored in consecutive locations starting from index 0.

Alternately, define an array as a set of index-value pairs as follows:

array_var[0]=”test1″
array_var[1]=”test2″
array_var[2]=”test3″

2. Print the contents of an array at a given index using the following commands:

echo ${array_var[0]}
test1
index=2
echo ${array_var[$index]}
test3

3. Print all of the values in an array as a list using the following commands:

$ echo ${array_var[*]}
test1 test2 test3

Alternately, you could use:

$ echo ${array_var[@]}
test1 test2 test3

4. Print the length of an array (the number of elements in an array) as follows:

$ echo ${#array_var[*]}
3

Defining Associative arrays

  1. Declaring statement for associative array
$ declare -A ass_array

2. After the declaration, elements can be added to the associative array using two methods as follows:

  • By using inline index-value list method, we can provide a list of index-value pairs:
  • Alternately, you could use separate index-value assignments:
$ ass_array=([index1]=val1 [index2]=val2)
$ ass_array[index1]=val1
$ ass_array'index2]=val2

3. Arrays have indexes for indexing each of the elements. Ordinary and associative arrays differ in terms of index type. We can obtain the list of indexes in an array as follows:

$ echo ${!array_var[*]}

alternatively, we can also use:

$ echo ${!array_var[@]}

Functions and Arguments

We can create functions to perform tasks and we can also create functions that take parameters (also called arguments) as you can see in the following steps:

  1. A function can be defined as follows :
syntax to use:
 syntax1:
 function function_name
 {
 ##set of commands
 }
 syntax2:
 function_name()
 {
 ##set of commands
 }
#!/bin/bash

var1='Hello'
var2='Knolders'

my_function () {
  local var1='Hi'
  var2='everyone'
  echo "Inside function: var1: $var1, var2: $var2" # var1: Hi var2: everyone
}

echo "Before executing function: var1: $var1, var2: $var2" 
# var1: Hello var2: Knolders

my_function

echo "After executing function: var1: $var1, var2: $var2" 
# var1: Hello  var2: everyone
   

2. One can invoke the function just by using its name:

$ fname ; # executes function

3. You can pass the arguments to the function and can access.Arguments can be passed to functions and can be accessed by our script:

fname arg1 arg2 ; # passing args

Following is the definition of the function fname . In the fname function, we have included various ways of accessing the function arguments.

fname()
{
echo $1, $2; #Accessing arg1 and arg2
echo "$@"; # Printing all arguments as list at once
echo "$*"; # Similar to $@, but arguments taken as single entity
return 0; # Return value
}

Similarly, you can pass the arguments to the script and you can access it by script:$0 (the name of the script):

  • $1 is the first argument
  • $2 is the second argument
  • $n is the nth argument
  • “$@” expands as “$1” “$2” “$3” and so on
  • “$*” expands as “$1c$2c$3” , where c is the first character of IFS
  • “$@” is used more often than “$*” since the former provides all arguments as a single string

Iterators/Loops

Loops are very useful in iterating through a sequence of values. Bash provides many types of loops. Let us see how to use them:

Using a for loop (SYNTAX):

for var in list;
do
commands; # use $var
done
list can be a string, or a sequence.
#Start of for loop
for a in 1 2 3 4 5
do
	# if a is equal to 5 break the loop
	if [ $a == 5 ]
	then
		break
	fi
	# Print the value
	echo "Iteration no $a"
done

While loop (SYNTAX):

while condition
do
commands;
done

For an infinite loop, use true as the condition.

Using an Until Loop (SYNTAX) :

A special loop called until is available with Bash. This executes the loop until the given condition becomes true. You can see the following example.

x=0;
until [ $x -eq 9 ]; # [ $x -eq 9 ] is the condition
do
let x++; echo $x;
done

Conditional Control

Using an if condition (SYNTAX):

if condition;
then
commands;
fi

Using else if and else (SYNTAX):

if condition;
then
commands;
else if condition; then
commands;
else
commands;
fi
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ] #-gt is comparator for greater than
then
   echo "a is greater than b"
elif [ $a -lt $b ] #-lt is comparator for less than
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

This is the end of this blog. Was it helpful? We will be glad to know your opinion and answer your queries. For more amazing blog visit knoldus blogs.

Written by 

Saumya is a Software Consultant at Knoldus Software LLP. She has done B.Tech from Quantum School of Technology, Roorkee. She has good knowledge of Devops technologies like Ansible, Terraform, Docker, Concourse, Jenkins, Kubernetes. She is very enthusiastic and energetic. Apart from technology, she is interested in various sports.