HomeTechnologyIntro to the incredible world of Shell scripting

Intro to the incredible world of Shell scripting

[*][*]

Reading Time: 7 minutes

Shell Scripting

A shell script uses the Linux instructions to perform a particular task. It provides loop and conditional control buildings that repeat Linux instructions or make decisions on which instructions 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 simpler to perform. Its simpler to get initiated with it. System admins use shell scripting for routine backups and various other tasks.

Shell

A shell, by definition, is an interpretive environment inside which you execute instructions. It provides users with an interface and accepts human-readable instructions into the system and executes those instructions which can run routinely and give the program’s output. When you run the terminal, the Shell issues a command prompt (usually $), where you can type your enter,(instructions) 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.

1627214286 643 Intro to the incredible world of Shell scripting

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 broadly 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 pupil at University of California, Berkeley in the late 1970s. The C shell’s syntax and utilization are very identical 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 specs 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 start 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.

1627214286 954 Intro to the incredible world of Shell scripting
1627214286 782 Intro to the incredible world of Shell scripting

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 sure 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 immediately. 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 seen 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 identical 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
legitimate=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 10 ];
then
break
fi
((count++))
done
1627214287 976 Intro to the incredible world of Shell scripting

Run the file.

1627214287 933 Intro to the incredible world of Shell scripting

Arrays and associative arrays

Arrays are a very necessary 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 helps associative arrays that can take a string as their array index. To use associate arrays, you should 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 instructions:

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 instructions:

$ 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

1627214287 264 Intro to the incredible world of Shell scripting
1627214288 435 Intro to the incredible world of Shell scripting

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 2 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 instructions
 }
 syntax2:
 function_name()
 {
 ##set of instructions
 }
#!/bin/bash

var1='Hello'
var2='Knolders'

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

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: everybody
   

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 entry.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 "[email protected]"; # Printing all arguments as list at once
echo "$*"; # Similar to [email protected], but arguments taken as single entity
return 0; # Return value
}

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

  • $1 is the first argument
  • $2 is the second argument
  • $n is the nth argument
  • [email protected]” expands as “$1” “$2” “$3” and so on
  • “$*” expands as “$1c$2c$3” , where c is the first character of IFS
  • [email protected]” 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
instructions; # 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 situation
do
instructions;
done

For an infinite loop, use true as the situation.

Using an Until Loop (SYNTAX) :

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

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

Conditional Control

Using an if situation (SYNTAX):

if situation;
then
instructions;
fi

Using else if and else (SYNTAX):

if situation;
then
instructions;
else if situation; then
instructions;
else
instructions;
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 situation 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 incredible blog visit knoldus blogs.

1627214288 262 Intro to the incredible world of Shell scripting


[*]Go to the source

Most Popular