Shell script

Shell scripts use Linux commands to perform a specific task. It provides loops and conditional control structures to repeat Linux commands or make decisions about which commands you want to execute. If you already have some programming experience, it will be very easy to learn (a very basic level is ok too).

Shell scripts provide automation, making repetitive tasks, system monitoring easier to perform. It’s easier to get started. System administrators use shell scripts for regular backups and a variety of other tasks.

shell

By definition, a shell is an interpreted environment in which you execute commands. It provides the user with an interface and accepts human-readable commands into the system, executes those commands that can be run automatically, and gives the output of the program. When you run the terminal, the Shell emits a command prompt (usually $), where you can type your input, and then execute it when you hit Enter. After that, the output or results are displayed on the terminal. Consider the following image, which lists all the items when the ls command is issued.

Type of shell

There are different types of shells available for Linux distributions.

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

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

echo $SHELL
Copy the code

The $sign represents a shell variable, and echo will return whatever text you enter.

How to write shell scripts?

You can use a text editor to write shell scripts. On your Linux system, open a text editor program, open a new file and start typing a shell script or shell program. Then give the shell permission to execute your shell script.

Let’s walk through the steps to create a Shell script.

  1. Use the VI editor (or any other editor) to create a file.
  2. Name the file with the extension **.sh**.
  3. With * * #! /bin/sh**(She-bang).
  4. Write some code.
  5. Save the script file.
  6. Run chmod +x<**fileName>.**sh to make the script executable.
  7. To execute the script, type bash.sh or./

    .sh. * * * *

Note: We can run the script as a command-line argument to bash, or we can grant execution permission to the script, making it executable.

Shebang

Sign # * *! It’s called a she-bang, and it’s written at the beginning of the script. It passes instructions to #! ** The corresponding program.

To run your script in a specific shell (which your system should support), start your script with #! Follow the name of the shell.

#! /bin/bash echo Hi Knolders #! /bin/ksh echo Hello KnoldusCopy the code

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 only be called by the Shell. Here is a small script that will use variables. Scripting languages generally do not require variable type declarations before use because they can be assigned directly. In addition, there are variables that are used by shell and operational environments to store special values. These variables are called environment variables.

To see all the environment variables associated with the terminal, issue the env command. Some well-known environment variables are HOME, PWD, USER, UID, SHELL, and so on.

env
Copy the code

For each process, its runtime environment variables can be viewed.

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

In the script above, you can notice that ‘name’ and ‘address’ are variables that can be used with $<variable_name>.

Let’s execute a shell script

Try to execute the given code in a similar manner as above and observe the output. Create a bash file named **”while_loop.sh “to see how while loops are used. In this example, the while loop will iterate 10 times. The value of the count variable is incremented by 1** at each step. The while loop terminates when the value of the count variable reaches 10.

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

Run the file.

Arrays and associative arrays

Arrays are a very important component, and you can use indexes to store collections of data as separate entities. Ordinary arrays can only use integers as their array indexes. On the other hand, Bash also supports associative arrays, which can be indexed using strings. To use associative arrays, you must have Bash version 4 or later.

  1. You can define arrays in many ways. Define an array with a list of values in a row, as shown below.

Array_var =(1, 2, 3, 4, 5, 6)# Values will be stored in consecutive positions starting with index 0.

Alternatively, define the array as a set of index-value pairs, as shown below.

array_var[0]=”test1″

array_var[1]=”test2″

array_var[2]=”test3

2. Run the following command to print the contents of the array at the specified index:

echo {array\_var\[0\]} test1 index=2 echo {array_var[$index]}

test3

3. Print all the values in the array as a list with the following command:


e c h o echo
{array_var[*]}

test1 test2 test3

In addition, you can also use.


e c h o echo
{array_var[@]}

test1 test2 test3

Print the length of an array (the number of elements in the array), as shown below.


e c h o echo
{#array_var[*]}

3

Defining associative Arrays

  1. A statement that declares an associative array
$ declare -A ass_array
Copy the code

2. After the declaration, you can add elements to the associative array using the following two methods.

  • We can provide a list of index-value pairs by using the inline index-value list method.
  • Alternatively, you can use separate index-value assignments.
$ ass_array=([index1]=val1 [index2]=val2)
Copy the code
$ ass_array[index1]=val1
$ ass_array'index2]=val2
Copy the code

3. Arrays have indexes to index each element. Ordinary and associative arrays differ in index types. We can get a list of indexes in an array as follows.

$ echo ${! array_var[*]}Copy the code

Or, we can use.

$ echo ${! array_var[@]}Copy the code

Functions and parameters

We can create functions to perform tasks, and we can also create functions that take arguments (also called arguments), as you can see in the steps below.

  1. A function can be defined as follows:
syntax to use:
 syntax1:
 function function_name
 {
 ##set of commands
 }
 syntax2:
 function_name()
 {
 ##set of commands
 }
Copy the code
#! /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: everyoneCopy the code

2. People can call this function by using its name.

$ fname ; # executes function
Copy the code

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

fname arg1 arg2 ; # passing args
Copy the code

Here is the definition of the function fname. In the fname function, we include various methods to access the parameters of the function.

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
}
Copy the code

Again, you can pass arguments to the script, which you can access from the script: $0 (the name of the script).

  • The first parameter is $1
  • $2 is the second argument
  • $n is the NTH argument
  • “$@” expands to “1”, “2”, “3” and so on
  • “\ *” extended to “1 c \ *” extended to “1 c \ *” extended to “1 c2c $3”, where c is the first character of the IFS
  • “@” is used more often than “@” than “@” because it supplies all of its arguments as a string.

Iterator/loop

Loops are useful for iterating over a series of values. Bash provides many types of loops. Let’s see how to use them.

Use for loop (SYNTAX):

for var in list;
do
commands; # use $var
done
list can be a string, or a sequence.
Copy the code
#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
Copy the code

The While loop (SYNTAX) :

while condition
do
commands;
done
Copy the code

For an infinite loop, use true as the condition.

Use the Until loop (SYNTAX):

Bash has a special loop called until. The loop continues until the given condition is true. You can see the example below.

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

Conditional control

Use the if condition (SYNTAX):

if condition;
then
commands;
fi
Copy the code

Using else if and else (SYNTAX):

if condition;
then
commands;
else if condition; then
commands;
else
commands;
fi
Copy the code
#! /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" fiCopy the code

That’s the end of this blog. Does it help? We would be happy to hear your comments and answer your questions.