Shell Scripting Tutorial

Are you looking for Linux/Unix shell programming tutorial? I think you are in the right place. Quicken your Linux/Unix shell scripting professional career with our recently developed Shell Scripting tutorial article. Linux or UNIX is an operating system and it is distributed under open-source license management. This operating system is designed on the Kernel source which can be used as a customized operating system. This Shell scripting tutorial article helps you to explore the different requirements and their advanced tool required by the Linux/Unix administration tools and also enables you to become a master in this tool. Are you ready to learn the most amazing shell technology? Then what you are waiting for, let’s begin:

What is Shell?

The shell acts as an interface between the user and the operating system. The shell consists of a single operating system that is Kernel this helps to run the scripts simultaneously. When a user enters the command using keyboards, the shell communicates with the kernel operating system and executes it, then displays the outputs to the users. In other words, we can say that a shell is nothing but a computer program that helps to expose an operating system service to human users or other programming languages. In normal, this type of shell use either a command-line interface or a GUI (graphical user interface), this depends on the particular operations or roles.

What is Shell

4 important concepts to be considered in a Shell:

  1. With the help of shell users can interact with systems.
  2. Using the script files several operations can be scripted by placing the respective operations.
  3. Shell can be differentiated as a featured programming language with script variables, and conditional statements.
  4. Shell allows users to create any UNIX program like any other programming language.

What do you know about Shell scripting?

Shell scripting is a series or sequence of Linux commands which are written in plain text format. Shell scripting in Linux is used to use of list various Linux commands instead of working with specific jobs or commands. The shell script is a computer interface type of program designed to be work on Linux or UNIX operating system. This is also known as a Command-line interpreter. The various form of shell scripts is now considered as scripting languages. The main purpose of using Shell script in Linux or UNIX includes manipulation of files, printing texts, and program execution.

Shell scripting

Why write a Shell script?

The following are the reason behind why we need Shell script;

  1. Shell scripts take input from users, file system, and output them on the screen.
  2. With the help of a shell script you can create your commands.
  3. Time-consuming and helps to automate some daily tasks.
  4. System administration part can also be automated with the help of the Shell script.

Shell Scripting Architecture overview:

Below diagram explains the overall structure of Linux or Unix Shell scripting:

Shell Architecture

A Linux/ UNIX shell offers an interface that lets the better user interactions with the operating systems by using command line arguments. But Shell scripting in Linux is also a rich programming language. The methods included are flow control, looping, conditionals, named functions, alternation, basic mathematical operations, and two-way communication between shell architecture and commands. The shell can also be used as a terminal or terminal emulator such as Xterm and also reads the commands from a file. Shell supports bash, command-line editing, emacs, or vi-like commands. The main operations in shell pipeline such as reading the input command from the terminal or a script form, the input data is passed through various stages, transformed to each stage, then shell finally executes a command, and collects the return status.

Why we need Shell scripting command?

Below are a few advantages of using shell scripting:

  1. Thousands of commands included with Fedoras are available in the form of shell scripts. For example: startx command.
  2. Shell script can save the user time and typing, suppose if you are using the same command lines multiple times each day.
  3. A shell program is smaller in size than any compiled program.
  4. The process of creating and testing your shell script command is also simpler and faster than any development compiling process.
  5. You can learn hundreds of commands when compare to other compiling programming languages.
How to determine a Shell?

You can name your first shell prompt by using the following command:

Syntax:

Echo $SHELL

For Example:

How to determine a Shell

Where $ sign indicates the shell variable and Echo returns the text what you typed in the command line interpreter.

Shell variables:

A shell variable is a type of character string that is used to assign a value. The assigned values can be available in the form of text, number, device, filename, or any other data type. In simple terms, we can define the variable as a pointer which is used as a pointer to refer to actual data types.

Variable names:

The variable name can contain letters from ( a to z or A to Z), numbers ( 0 to 9), or the underscore characters (_). When you are working with UNIX, shell variables have their names in UPPERCASE only.

For example: (valid variables names)

_ECHO

TOKEN _A

VAR_1

VAR_2

Following are the example for invalid variable names in Shell:

3_VAR

-VARIABLE

VAR1-VAR2

VAR_A!

While working with Linux, you cannot use characters like! , *, or – so they will be considered as an invalid variable.

Defining the variables in Shell:

The syntax is as follows:

Variable_name = variable_value

Example:

NAME = “Kavya”

Shell variables enable you to store any value, for example:

VAR1 = “Kavya”

VAR2 = 200

Accessing values:

To access any value stored in a variable, it should start with a prefix name along with a dollar sign ($);

The following example will explain this:

#! / bin/ sh

NAME = “Kavya”

echo $NAME

The above script will produce the following output:

KAVYA

Variable types:

Below are the types of variables:

1. Local variables:

A local variable is a type of variable present within the shell current instance values. These variables are not available to any shell program. They are usually set at the command prompt.

2. Environment variables:

The environment variables only at the child process level in the shell. Some shell programs make use of these environment variables in order to perform any function correctly.

3. Shell variables:

A shell variable is a special variable type that is used by only shell scripts. Some of the shell variables are environment variables whereas others are local variables.

Shell Scripting Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning
Special variables:

In the previous section, we have explained about basic variables used in the Shell script. Now it’s time to learn more about special variables, let’s get into it:

$ -> this character represents the ID number used to process any special character of the current shell.

For example:

$echo $$

$0 -> this character represents the current script filename

$n -> these variables represents the arguments. Here n is a positive decimal number and also represents the position of an argument. For example, $1 represents the first argument, $2 represents the second argument, and so on.

$# -> this character supplies the number of arguments to the scripts.

$* -> with the help of this character we can double-quote the important script value.

[email protected] -> this character helps to make the individual argument double-quoted. Suppose if you get [email protected] is equivalent to $1 $2.

$? -> This represents the status of the last command argument to be executed.

$$-> this character represents the process number of the current shell.

$! -> This represents the last background command process number.

Programming example:

#!/bin/sh

Echo “file name: $0”

Echo “first parameter: $1”

Echo “second parameter: $2”

Echo “quoted values: [email protected]

Echo “quoted values: $*”

Echo “total number of parameters used: $#”.

Output:

$./test.sh KAVYA GOWDA

File name: ./test.sh

First parameter: KAVYA

Second parameter: GOWDA

Quoted values: KAVYA GOWDA

Quoted values: KAVYA GOWDA

Total number of parameters: 2
Shell arrays:

Shell script supports various types of special variables they are known as array variables. This type of array consists of multiple values at the same time. Array variable in script offers a grouping of various variable sets. The important purpose of using this array variable is instead of creating a new name for each variable, just use a single array variable to store all kinds of shell variables.

Defining array values:

The following example will explain how you define the array values,

NAME01 = “KAVYA”

NAME02 = “GOWDA”

NAME03 = “RAKSHITH”

NAME04 = “INDIA”

NAME05 = “BANGALORE”

We can use a single array value used to store the mentioned names. The following method will explain this;

Array_name [index] = value

Here array_name is the name of the array value, the index is the index of the item in the array set, and value is the name of the value which you want to set for the items.

Use the following command to set the array values:

NAME [0] = “KAVYA”

NAME [1] = “GOWDA”

NAME [2] = “RAKSHITH”

NAME [3] = “BANGALORE”

NAME [4] = “INDIA”

Accessing Array Values:

Once you are done with defining array variables, you access them as follows:

${array-name [index]}

Here array_name is the name of the array, and index is the index of the value to be accessed. Following is an example to access the array values:

#! /bin/sh

NAME [0] = “KAVYA”

NAME [1] = “GOWDA”

NAME [2] = “RAKSHITH”

NAME [3] = “BANGALORE”

NAME [4] = “INDIA”

Echo “first index: ${NAME [0]}”

Echo “second index: ${NAME [1]}”

The above example generates the following result:

$. /test.sh

First Index: KAVYA

Second Index: GOWDA

You can also access the items in this way:

$ {array_name [*]}

${array_name [@]}

Subscribe to our youtube channel to get new updates..!

Shell basic operators:

There are various operators supported by a shell interpreter. The following are the basic operators of Shell.

  1. Arithmetic operators
  2. Relational operators
  3. Boolean operators
  4. String operators
  5. File test operators

First, let me start with

Arithmetic operators:

The following are the different types of arithmetic operators:

+ (addition): this operator is used for the addition of any variables.

- (subtraction): this operator is used to find the differences between any two variables.

*(multiplication): multiplies values on either side of the operators.

/ (Division): this operator divides the left-hand operand by the right hand operands.

%( Modulus): this operator is used to divides the left-hand operands by any right hand operand and return the remainder.

= (Assignment): this operator is used to assign the right hand operand is left operands.

== (Equality): this operator compares any two numbers, if both are the same then returns the true value.

!= (Not equality): compares any two numbers, if both are different then return the true value.

Relational operators:

The following are the different types of relational operators used:

-eq: this operator checks if the two operand values are equal or not, if yes, then the condition becomes true.

-ne: this operator checks if the value of any two operands are equal or not, if the given values are not equal, then the condition becomes true.

-gt: this operator is used to check if the left operand value is greater than the value of right-hand side operand, if yes then the condition becomes true.

-lt: this operator is used to check if the left operand value is lesser than the value of the right hand side operand, if yes then the condition becomes true.

-ge: this operator checks if the value of the left operand is greater than or equal to the right operand value, if yes, then the condition becomes true.

-le: this operator checks if the value of the left operand is less than or equal to the right operand value, if yes, then the condition becomes true.

Boolean operators:

The following are the different types of Boolean operators supported by Shell:

!: This is also known as logical negation. This operator converts a true condition into false, and vice versa.

-o: this is a logical OR operator. If one of the operand values is true, then the condition becomes true. Then the given condition becomes true.

-a: this is a logical AND operator. If both the operands are true, then the given condition becomes true otherwise false.

String operators:

The following are important types of string operators supported by Shell:

=: this operator checks if the given two operand values are equal or not, if yes, then the given condition becomes true.

!=: this operator checks if the value of any two operators are equal or not, if the given values are not equal then the given condition.

-z:  this string operator checks if the given string operand is zero, if it is in zero-length, then the condition becomes true.

-n: this string operator checks, if the given string operand is non-zero, if it is in non-zero length, then this operator returns true.

Str: this operator checks if the str is a non-empty value, if the given string value is empty, then it returns false.

File test operators:

The following are the important file test operators by the shell:

-b file: this operator checks if the file blocks any specified file type, then the condition becomes true.

-c file: this operator checks if the file is a special character, then the given condition becomes true.

-d: this operator checks if the file is a directory, then the condition becomes true.

-f file: this operator is used to check if the file is an ordinary type, then the given condition becomes true.

-g file: this file operator checks, if the file has its own set of groups if, if yes, then the condition becomes true.

-k file: this operator checks if the file has its sticky bit type, if yes, then the given condition becomes true.

-t file: this operator checks if the file descriptor type is open and associated with any terminal, then the given condition becomes true.

-u file: this operator checks if the file has its own set User ID, if yes then the condition becomes true.

-r file: this operator checks if the file is readable or not, if yes then the condition becomes true.

Shell decision making:

Unix/Linux supports two types of conditional statements, which are used to perform various actions based on the conditions. Now we are going to discuss two types of decision making:

  1. The if …. Else statements
  2. The case …. Esac statement

First, start with if ….. Else statements:

These condition statements are useful decision-making statements, which are useful to select any option from the given set of options.

In the shell, you can see a different type of if….else statements:

  1. If ….fi statement
  2. If….else…fi statement
  3. If….elif...else…fi…statement

Most of the if conditional statements use the relational operators.

The case….esac statement:

Here you can use multiple if….elif statements used to perform multiple branch operations. However, sometimes, this type of condition statement is not always the best, when a branch depends on the value of any single variable.

To overcome this problem, UNIX has come up with a case….esac conditional statement, and it works better than if….elif statements.

The caseesac statement in the UNIX is similar to the switch…case statement which is used in many programming languages like C, C++, And PERL, etc.

Shell looping types:

Till now I have explained what types of conditional statements are used in Shell, now it’s time to learn about looping statements.

There are 4 types of loops available based on the situations:

  1. While loops
  2. The for loops
  3. The until loops
  4. The select loops

We already know about While and for loops, the while loop executes the statements until the condition is true, if the given condition fails, then it terminates the loop. The while and for loops are available in most of the other well-known programming languages like C, C++, and PERL, etc.

Nesting loop:

All the basic loops support the nesting concepts; nesting means you can put multiple loops inside (similar or different ones). The nesting can be used an unlimited number of times as per your requirements.

Below is an example for Nesting while loops:

While command1;   /./ this one is for outer loop

  Do

Statement (s) to be executed if the command1 condition is true

While command2; // this one is for loop2, the inner loop command

   Do

Statement (s) to be executed if the command2 condition is true

Done

Statement (s) to be executed if the command1 condition is true

Done

Explore Shell Scripting Sample Resumes Download & Edit, Get Noticed by Top Employers! 

Shell loop controls:

In this section, you will be learning important two statements that are used to control shell loops:

  1. The break statement
  2. The continue statement

First start with continue or infinite loop statement:

As we know that all the loops have a limited life span and they come out of the loop if the given condition is false or depends on the loop.

This type of loop statement may continue if the required condition is not met the given condition. A loop executes forever without terminates for an infinite number of times. This type of loop statement is known as an infinite or continues the loop.

Example:

#! / bin/ sh

a = 20

until [$a  -lt  20]

do

  echo $a

   a = expr $a + 1

done

The loop continues forever because a is always greater than or equal to 20 and it is never less than 20.

The break statements:

The break statement in the shell is used to terminate the execution of the whole loop once finishes the execution of all line codes executed successfully. If that does not meet the given condition then terminates the program.

Syntax:

The following statement is used to come out of the loop:

break

The following statement is used for the nested loop condition:

break n

Where n specifies the nth enclosing loop which is an exit from.

Example:

#!  /bin/sh

a = 0

while [$a  -lt  10]

do

  echo $a

 If [$a -eq 6]

then

   break

fi

  a = expr $a + 1

done

Output:

0

1

2

3

4

5

6

Shell Scripting Training Certification

Weekday / Weekend Batches

The continue statement:

You can say that the continue statement is similar to the break command, and this continue statement causes the current loop iterations to exit, rather than the whole loop. This continue statement is useful when an error has occurred.

Syntax:

Continue

To execute n number of iteration loop the syntax is as follows:

Continue n

The programming example is as follows:

#!/bin/sh

NUMS = “1 2 3 4 5 6 7 8”

For NUM in $NUMS

do  

  Q = ‘expr $NUM % 2’

  If [$Q –eq 0]

 Then

   Echo “number is an even number!!”

      Continue

     Fi

   echo “found odd number in the result”

Done

Output:

Found odd number in the result

Number is an even number!!

Found odd number in the result

Number is an even number!!

Found odd number in the result

 number is an even number!!
Shell substitution:

When the shell program encounters an expression by that time substitution can be used. This substitution contains one or more special characters.

The following are the few special characters that are supported by the shell:

\\: backlash

\a: alert

\b: backspace

\c: suppress trailing newline character

\f: form feed

\n: new line

\r: carriage return

\t: horizontal tab

\v: vertical tab

Variable substitution:

Variable substitution helps shell programmers to manipulate the variable value on the basis of the state.

The following are a few examples for variable substitutions:

${var}: substitute the value of var or variable

${var: word} = if the var is null or unset condition, then the word is substituted for var. Here the values of var never change.

${var:? message} = if the var is the null or unset condition, then the message ids printed to the standard error. This also checks for the variables are set correctly or not.

${var:+word} = if the variable is set, the word is substituted for var. The value of var does not change in the program.

Shell files systems:

A file system is nothing but logical collections of various files or disks. Everything in UNIX is considered to be a file, for example, DVD-ROMs, USB devices, and any other floppy devices.

The following are the examples for a file system:

/ = this indicates the root directory which contains only directories at the top level.

/bin = this expression indicates the executable files are located. These types of files are available to all users.

/dev = this indicates the device drivers.

/etc = this contains supervisor directory commands, disk configuration files, valid user lists, and Ethernets.

/lib = contains shared library files and also kernel-related files.

/boot = this contains boot file system.

/usr = this files type for miscellaneous purpose, and used by many users, for example administrative commands, library files, shared files, and others.

/kernel = consists only kernel file types.

Conclusion :

In this shell scripting tutorial, we have explained the definitions, architectures, conditional statements, decision makings, and file system types. From this tutorial, you will gain more knowledge related to UNIX OR Linux shell script program. To become a master in this technology, you must take any course related to LINUX or UNIX. What you are waiting for, let’s begin your shell script programmer journey.

Find our upcoming Shell Scripting Training Certification Online Classes

  • Batch starts on 5th Jun 2023, Weekday batch

  • Batch starts on 9th Jun 2023, Fast Track batch

  • Batch starts on 13th Jun 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Saritha Reddy
Saritha Reddy
Research Analyst
A technical lead content writer in HKR Trainings with an expertise in delivering content on the market demanding technologies like Networking, Storage & Virtualization,Cyber Security & SIEM Tools, Server Administration, Operating System & Administration, IAM Tools, Cloud Computing, etc. She does a great job in creating wonderful content for the users and always keeps updated with the latest trends in the market. To know more information connect her on Linkedin, Twitter, and Facebook.