02 - ShellScripting Documentation - 2022
02 - ShellScripting Documentation - 2022
DOCUMENTATION
Mithun Technologies, +91 99809 23226, devopstrainingblr@[Link]
Shell is a program that takes commands from the keyboard and gives them to the operating
system to perform.
On most Linux systems a program called bash (which stands for Bourne Again SHell, an
enhanced version of the original Unix shell program, sh, written by Steve Bourne) acts as the
shell program. Besides Bourne shell, there are other shell programs that can be installed in a
Linux system. These include Korn Shell (ksh), Boune Again Shell (bash), and C Shell (csh)
C Shell (csh)
Developed by Bill Joy from Berkley University is the most common Shell on
*BSD/Xenin environments. Commands structure is very similar to the C programming language.
Its major fault was that it is not compatible with the sh Shell.
tcsh or TENEX C shell: a superset of the common C shell, enhancing user-friendliness and
speed. That is why some also call it the Turbo C shell.
Your default shell is set in the /etc/passwd file, like this line for user Test.
Test:x:510:512:Test ID:/home/Test:/bin/bash
To create a shell script, you use a text editor. There are many, many text editors available for
your Linux system, both for the command line environment and the GUI environment. Here is a
list of some common ones:
1) vi or vim is the command line interface text editor.
2) gedit is the GUI text editor.
Example:
#vi [Link] // Start vi editor
#gedit [Link]
Step 2) After writing shell script set execute permission for your script as follows
Syntax: chmod << permission >> <<script file name >>
Examples:
# chmod +x script file name
# chmod 755 script file name
Note: This will set read, write and execute (7) permission for owner, for group and other
permissions are read and execute only (5).
./[Link]
Output:
Hello welcome to Shell Script!”
#!/bin/bash
#Purpose : To display the message.
#Author: Mithun Reddy Lacchannagari.
#Date: 24th June 2010.
The first line is called a shebang or a "bang" line. It is nothing but the absolute path to the Bash
interpreter. It consists of a number sign and an exclamation point character (#!), followed by the
full path to the interpreter such as /bin/bash.
If you do not specify an interpreter line, the default is usually the /bin/sh.
In order to execute the shell script make sure that you have execute permission. Give execute
permissions as follows.
Case Sensitivity
As you know Linux is case sensitive, the file names, variables, and arrays used in shell scripts
are also case sensitive.
#!/bin/bash
string1=10
String1=20
echo "The value of string1 is $string1 "
echo "The value of String1 is $String1 "
[Link]
[Link]
[Link]
[Link]
Mithun_08112013.sh
[Link]
Comments
<<COMMENT1
your comment 1
comment 2
blah
COMMENT1
Variables
1) Variable name must begin with alphanumeric character or underscore character (_).
Following are the few examples for variable.
name="MithunTechnologies"
training="DevOpsMasterProgram"
By convention, environment variables (PAGER, EDITOR, ..) and internal shell variables
(SHELL, BASH_VERSION, ..) are capitalized. All other variable names should be lower case.
Remember that variable names are case-sensitive; this convention avoids accidentally overriding
environmental and internal variables.
Do not put spaces on either side of the equal sign when assigning value to variable. For example,
the following is valid variable declaration:
no=10
However, any of the following variable declaration will result into an error such as command not
found:
no =10
no= 10
no = 10
no=10
No=11
NO=20
nO=2
All are different variable names, to display value 20 you've to use $NO variable:
You can define a NULL variable as follows (NULL variable is variable which has no value at
the time of definition):
tech=
tech=""
echo $tech
Do not use ?,* and other special characters, to name your variable.
?no=10 #invalid
out*put=/tmp/[Link] #invalid
_GREP=/usr/bin/grep #valid
echo "$_GREP"
Created and maintained by Linux bash shell itself. This type of variable is defined in CAPITAL
LETTERS.
There are many shell inbuilt variables which are used for administration and writing shell scripts.
To see all system variables, type the following command at a console / terminal:
env or printenv
#! /bin/bash
echo 'BASH='$BASH
echo 'BASH_VERSION='$BASH_VERSION
echo 'HOSTNAME=' $HOSTNAME
echo 'TERM='$TERM
echo 'SHELL='$SHELL
echo 'HISTSIZE='$HISTSIZE
echo 'SSH_CLIENT='$SSH_CLIENT
echo 'QTDIR='$QTDIR
echo 'QTINC='$QTINC
echo 'SSH_TTY='$SSH_TTY
echo 'RE_HOME='$JRE_HOME
echo 'USER='$USER
echo 'LS_COLORS='$LS_COLORS
echo 'TMOUT='$TMOUT
echo 'MAIL='$MAIL
echo 'ATH='$PATH
echo 'PWD='$PWD
echo 'JAVA_HOME='$JAVA_HOME
echo 'LANG='$LANG
echo 'SSH_ASKPASS='$SSH_ASKPASS
echo 'HISTCONTROL='$HISTCONTROL
echo 'SHLVL='$SHLVL
echo 'HOME='$HOME
echo 'LOGNAME='$LOGNAME
echo 'TLIB='$QTLIB
echo 'CVS_RSH='$CVS_RSH
echo 'SSH_CONNECTION='$SSH_CONNECTION
echo 'LESSOPEN='$LESSOPEN
echo '_BROKEN_FILENAMES='$G_BROKEN_FILENAMES
echo 'OLDPWD='$OLDPWD
Created and maintained by user. This type of variable defined may use any valid variable name,
but it is good practice to avoid all uppercase names as many are used by the shell.
id=05211P
echo 'Displaying the user defined the varibale (trainingCourse) value is: '$trainingCourse
During shell script execution, values passing through command prompt is called as command
line arguments.
For example, while running a shell script, we can specify the command line arguments as “sh
[Link] arg1 arg2 arg3”
While using command line arguments follow the below important points.
#!/bin/sh
#Number of arguments on the command line.
echo '$#:' $#
#Process number of the current process.
echo '$$:' $$
#Display the 3rd argument on the command line, from left to right.
echo '$3:' $3
#Display the name of the current shell or program.
echo '$0:' $0
#Display all the arguments on the command line using * symbol.
echo '$*:' $*
#Display all the arguments on the command line using @ symbol.
echo '$*:' $@
Escape character
When using echo -e, you can use the following special characters:
\\ backslash
\a alert (BEL)
\b backspace
\c suppress trailing newline
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
Example:
Strings
Example:
FileName: [Link]
#!/bin/bash
single='Single quoted'
double="Double quoted"
echo $single
echo $double
String Formatting
Character Description
-n Do not output the trailing new line.
-e Enable interpretation of the following backslash escaped characters in the strings:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash
Example:
#!/bin/bash
echo -e "Hello \t Welcome to Linux Shell Scripting"
Arithmetic Operations
Syntax:
expr op1 math-operator op2
Example:
FileName: arithmetic_operations.sh
$ expr 3 + 2
$ expr 3 - 2
$ expr 10 / 2
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 3 + 2`
In shell scripting we will be using the echo command to print the result of the arithmetic
operations.
Note:
If you use echo command, before expr keyword we use ` (back quote) sign.
Here both double and single quote will not give you the desired result.
Try the following commands:
From the above example, we see that if we use double or single quote, the echo command
directly prints " expr 3 + 2 ".
To get the result of this expression, we need to use the back quote.
In some cases the script needs to interact with the user and accept inputs.
In shell scripts we use the read statement to take input from the user.
read : read command is used to get the input from the user (Making scripts interactive).
Following shell script demonstrates the take the input from user and display that back to
user.
#!/bin/bash
#Author: Bhaskar Reddy Lacchannagari.
Output:
Please enter your name: Bhaskar Reddy L
The name you entered is Bhaskar Reddy L
Output:
Debugging
For debugging the shell we can use –v, -x and –n options. General syntax is as follows.
Following shell script will accept the numbers from command prompt and, it will display the
sum of those two numbers.
#! /bin/sh
#Purpose: Addition of two numbers
#Author: Bhaskar Reddy Lacchannagari
#Date: June 24th 2010
sum=`expr $1 + $2`
echo $sum
#sh -v [Link] 1 2
#sh -x [Link] 1 2
#sh -n [Link] 1 2
Bash shell offers debugging options which can be turned on or off using set command as
follows.
#!/bin/sh
#Purpose: Addition of two numbers
#Author: Bhaskar Reddy Lacchannagari
#Date: June 24th 2010
set -x
//set -v
//set -n
sum=`expr $1 + $2`
echo $sum
#sh [Link] 1 2
Example:
ls > [Link]
The above command will redirect the output of the " ls " to the file " ls-file ".
If the file " ls-file " already exist, it will be overwritten. Here you will loose the existing data.
Example:
date >> [Link]
The output of the date command will be appended to the file " ls-file ".
In this case you will not loose any data. The new data gets added to the end of the file.
Example:
cat < [Link]
Some of the forms of redirection for the Bourne shell family are:
Character Action
2> Redirect standard error
2>&1 Redirect standard error to standard output
Examples:
We can suppress redirected output and/or errors by sending it to the null device, /dev/null. The
example shows redirection of both output and errors:
Control commands
if control statement:
Syntax:
if condition
then
Display commands list if condition is true.
else
Display commands list if condition is false.
fi
Note: if and then must be separated, either with a << new line >> or a semicolon (;).
Termination of the if statement is fi.
Example:
Run:
sh [Link] 1 2 3
Output:
if [ -f $file_name ]
then
if [ -w $file_name ]
then
echo "Type something, To Quit type Ctrl +d"
cat >> $file_name
else
echo "The file do not have write permissions"
fi
else
echo "$file_name not exists"
fi
-----------------------------------------------------------------------------------------------------
for loop
Syntax:
for (condition )
do
execute here all command/script until the condition is
not satisfied.(And repeat all statement between do and done)
done
Example:
FIleName: for_loop.sh
echo "Can you see the following:"
Output:
5
-----------------------------------------------------------------------------------------------------
while loop
Syntax:
while [ condition ]
do
command1
command2
command3
..
....
done
Example:
i=5
while test $i != 0
do
echo "$i"
echo " "
i=`expr $i - 1`
Output:
1
---------------------------------------------------------------------------------------------------------------------
----
switch case:
The case statement is good alternative to multilevel if-then-else-fi statement. It enables you to
match several values against one variable. It’s easier to read and write.
Syntax:
case $variable-name in
pattern1) command
...
..
command;;
pattern2) command
...
..
command;;
patternN) command
...
..
command;;
*) command
...
..
command;;
esac
Filename: switch_case.sh
#!/bin/sh
case $NUM in
1) echo "You entered is one" ;;
2) echo "You entered is two" ;;
3) echo "You entered is three" ;;
4) echo "You entered is four" ;;
5) echo "You entered is five" ;;
6) echo "You entered is six" ;;
7) echo "You entered is seven" ;;
8) echo "You entered is eight" ;;
9) echo "You entered is nine" ;;
10) echo "You entered is ten" ;;
---------------------------------------------------------------------------------------------------------------------
----
Functions:
When your scripts start to become very large, you may tend to notice that you are repeating code
more often in your scripts. You have the ability to create functions inside of your script to help
with code reuse. Writing the same code in multiple sections of your script can lead to severe
maintenance problems. When you fix a bug in a section of code you need to be sure that all
sections of code that are repeated will also have those fixes. A function is a block of code that
can be called from other parts of your script. It can have parameters passed to it as if it were a
separate script itself. As an example, we will create a function called log it, which will take two
parameters, a level and a message. The level will be a number between 1 and 3 that will indicate
the severity of the log message. The level of messages that you want to view will be passed in
the command line of the script.
Syntax:
function_name() {
Example:
FileName: [Link]
#!/bin/bash
greetfn(){
greetfn
-----------
FileName: [Link]
#!/bin/bash
addfn(){
}
echo "Calling greetfn() ! "
addfn 1 2
Pipes:
A pipe is nothing but a temporary storage place where the output of one command is stored and
then passed as the input for second command. Pipes are used to run more than two commands
(Multiple commands) from same command line.
Pipelines connect the standard output of one command directly to the standard input of another.
The pipe symbol (|) is used between the commands:
Example:
Creating a new file " friends ".
Result:
MITHUN
RUTHIK
MOURYA
SHISHIR
MANAN
The above command has sorted the file " friends " and using pipe the output was translated to
upper-case letters and then redirected its output to the file " FRIENDS ".
Filters
A filter is a program that accepts input, transforms it or does something useful with it and outputs
the transformed data. Some important filter commands are awk, tee, grep, sed, spell, and wc.
Example:
Process
What is Process?
Process is kind of program or task in execution.
Each command, program or a script in linux is a process.
Managing a process
You might have seen some process taking long time to execute. You can run such process in the
background.
Example:
ls / -R | wc -l
The above command can be used to find the total count of the files on your system. This takes a
long a time, so to get the command prompt and to start an other process, you can run the above
command in background
ls / -R | wc -l &
The ampersand (&) at the end of command tells the shell to run the command in background.
You will a number printed on your screen. It is the process Id.
So for each process you will have a process Id.