Shell Scripts• A Shell script: • Stores a sequence of frequently used Linux commands in a file • Enables the shell to read the file and execute the commands in it • Allows manipulation o
Trang 1In this lesson, you will learn to:
• Define the role and features of the Linux shell
• Use the shell as a command interpreter
• Create user-defined variables
• Use shell environment variables
• Create shell scripts in Linux
Trang 2Introduction to the Shell
• A shell:
• Is a utility program with
the Linux system that
• The adjacent figure shows
the architecture of the Linux
operating system
Trang 4Shell as a Command Interpreter
• The shell:
• Reads the command
• Locates the file in the directories containing utilities
• Loads the utility into memory
• Executes the utility
Trang 5Shell as a Command Interpreter (Contd.)
The shell creates a child shell for the execution of a utility
The shell requests the kernel for any hardware interaction
Trang 6Unix Shells
• Some of the popular Unix Shells are:
• Bourne Shell: sh is the executable filename for this shell
• C Shell: csh is the executable filename for this shell
• Korn Shell: The executable filename is ksh
• Restricted Shell: Is typically used for guest logins
Trang 7Linux Shells
• Some of the popular shells available in Linux are:
• Bash:
• Is an acronym for ‘Bourne Again Shell’ and is the default shell for
most Linux systems
• Uses the symbolic link sh
• Tcsh:
• Is an acronym for ‘Tom’s C shell’ also known as the TC shell
• It is an enhancement of the C shell
• Uses the symbolic link csh
• Can be executed by using either csh or tcsh at the shell prompt
• ASH:
• Is usually suitable on machines that have very limited memory
• Uses the symbolic link, bsh in Fedora Core 2
Trang 8Changing the Default Shell
• The default shell of the user is specified in the /etc/passwd file
• The chsh command can be used for changing the default shell for the user
[steve@linuxpc1 /etc]$ chsh Changing shell for Steve
Password:
New shell [/bin/bash]: /bin/cshShell changed
• The full path for the new shell has to be given when changing the shell
• After the default shell has been changed from Bash to csh, the entry for the
user, steve, in the passwd file changes as follows
steve:x:503:513:steve walker:/home/steve:/bin/csh
Trang 9Shell Scripts
• A Shell script:
• Stores a sequence of frequently used Linux commands in a file
• Enables the shell to read the file and execute the commands in it
• Allows manipulation of variables, flow-of-control and iteration constructs
that make programming possible
Trang 10The echo Command
• The echo Command
• Displays messages on the screen
• Displays the text, enclosed within double-quotes
• Puts a newline character at the end of the text by default
$ echo "This is an example of the echo command" This is an example of the echo command
$ _
Trang 11Executing a Shell Script
• A shell script can be executed:
• In a new shell by
1 First granting the execute permission to the specified shell script
2 Then invoking its name at the $ prompt
$ chmod u+x magic [Change File Access Permission]
$ magic [Execute the shell script]
• In the current shell by using the dot (.) command with the script name
in the Bash shell
$ magic [In the Bash shells]
Trang 12Creating Variables
• Variables in shell scripts:
• are not declared as integers or characters
• are treated as character strings
• can be mathematically manipulated
• do not have to be explicitly declared
• can be created at any point of time by a simple assignment of value
• The syntax for creating a variable is:
<variable name>=<value>
• Variables can be created:
• In shell scripts: A variable created within a shell script is lost when the
script stops executing
• At the shell prompt: A variable created at the prompt remains in
existence until the shell is terminated
Trang 13Referencing Variables
• The $ symbol is used to refer to the content of a variable
variable1=${variable2}
• The braces are essentially used to delimit the variable name
• The command to assign the value of today variable to x variable is:
$ x=$today
Trang 14Reading a Value into a Variable
• The read command is used to enter a value from the keyboard into a variable
during the execution of a shell script
• The syntax to use the read command is:
$ read <variable_name>
• The read command, on execution, waits for the user to enter a value for the
variable
• When the user presses <Enter> key after entering the value, the remaining part
of the shell script, if any, is executed
Trang 15Local and Global Shell Variables
• A local variable is a variable that can be given a different value in the child shell
without the parent shell knowing about it, as shown in the following example:
$ continent=Africa
$ echo "$continent"
Africa
$ bash [Creates a new shell]
$ echo "$continent" [There is no response]
$ continent=Asia [Gives new value Asia to continent]
$ echo "$continent"
AsiaPress <Ctrl> d
$ exit [Displays exit and returns to parent shell]
• The export variable is a global variable that is passed on by the export command
as an argument to all child shells
Trang 16Environment Variables
• All exported variables are environment variables, some of which are
meaningful to the shell
• By changing the values of these variables, a user can customize the
environment
• Some of the environment variables are:
• HOME: Stores the location of the HOME directory of a user
• PATH: Contains a list of colon-delimited path names of directories that
are to be searched for an executable program
• PS1: Contains the shell prompt, the $ symbol You can change the shell
prompt by setting the value of this variable to the desired prompt
• PS2: Sets a value for the secondary prompt, which is by default >
• LOGNAME: Contains the user’s login name
• SHLVL: Contains the shell level that you are currently working in
• SHELL: Stores the user’s default shell
Trang 17The env Command
• The env Command enables you to view the list of all the exported
environment variables and their respective values
• The following are some of the environment variables:
• HOME: Stores the location of the home directory of a user
• PATH: Contains a list of path names of directories that are to be
searched for an executable program
• PS1: Contains the shell prompt, $
• PS2: Sets the value of the secondary prompt
• LOGNAME: Contains the user’s login name
• SHLVL: Contains the shell level of the current shell
• SHELL: Stores user’s default shell
Trang 18In this lesson, you will learn to:
• Use the grave ascent, expr command, and test command
• Use conditional execution constructs
• Implement iteration constructs
• Use functions in shell scripts
• Debug shell scripts
• Handle parameters in shell scripts using positional parameters
• Implement the shift command
Trang 19• The test and [] Command
• Evaluates an expression and returns either a true (0) or a false (1)
• Can also be replaced with []
• Uses the following syntax:
test expression or [ expression ]
• Enables you to test multiple conditions in one command using the options -a and -o
• When using the wildcard characters the * is used, it should be preceded by a backslash (\), otherwise, the shell will interpret it as a wildcard character
Trang 20The if Construct
• Linux provides the if Construct to perform decision making in shell scripts
• The if construct is usually used in conjunction with the test command
Trang 21The exit Command
• The exit command is used to stop execution of the shell script and return to
the $ prompt based on the result of the test command
• The following example of the exit command example,
echo "Do you wish to quit?"
read ans
if [ $ans = "y" ]then exit
fi
• The exit command can also be used in the then part of the if…else
construct
Trang 22The case…esac Construct
• The case esac construct in Linux:
• Is often used in place of the if construct if a variable is tested against
command;;
value2) command
command;;
*) command;;
esac
Trang 23The while Construct
• The while Construct in Linux supports iteration in shell scripts
• The while construct has the following syntax:
while <condition>
do
<command (s)>
done
• The while true command, creates an infinite loop
• An example of the while construct is:
reply=ywhile test "$reply" != "n"
do
echo –n "Enter file name?"
read fnamecat ${fname}
echo –n "wish to see more files :"
read replydone
Trang 24The until Construct
• The evaluation pattern of the until loop construct is opposite to that of the
Trang 25The for Construct
• The for construct takes a list of values as input, and executes the loop for every
value in the loop
• The for construct has the following syntax:
for variable_name in <list_of_values>
do
…done
• The for construct supports wildcard characters in the list of values such as, *.c
• An example of the for construct is:
for name in Ruby Samueldo
echo "${name}"
done
Trang 26The break and continue command
• The break and continue commands are used with while loop
• The break command causes the termination of a loop
• An example of the break command is as shown below:
while truedo
echo "Enter choice"
echo "(press 'q' to exit)"
echo "1 date 2 who"
echo "3 ls 4 pwd"
read choice
case $choice in 1)date;;
• The continue command is used to resume execution in the while loop
Trang 27The test Command Revisited
• In the following example, the shell script accepts a file name from the user
and displays its file type using the test command:
echo –n "Enter file name: "
read fname
if test -f $fname
then echo "$fname is an ordinary file"
elif test -d $fname
then echo "$fname is a directory file"
elif test -s $fname
then echo "$fname is a not an empty file"
elif test ! –r "$fname"
then echo "No readable file called $fname exists"
fi
• In the preceding example, the –f, -d, and –s options represent files that
exist and are ordinary, directory, and not empty, respectively
Trang 28The shift Command
• The following shell script uses the shift command in parameter handling:
if test $# -eq 0
then echo "Arguments required"
exitfi
command=$1shift
if test $command = 'c'then
if test $# -ne 2then echo "Invalid number of arguments for copy"
else cp $1 $2fi
elif test $command = 'd'then
if test $# = 0then echo "Invalid number of arguments for delete"
else rm $*
fielse echo "Invalid argument - must be 'c' or 'd'"
fi
Trang 29The bash_profile File
• The bash_profile file is used to set the environment variable that are not
set automatically
• It is a special shell script that is executed as soon as the user logs in
• The bash_profile file contains the standard settings for the user such as,
the type and path of terminal being used
• The presence of this file is optional
• If it needs to be executed, it must exist in the user’s HOME directory
Trang 30Creating Functions
• A function:
• Is a block of statements that are referred to by a specific name and
perform a specific task
• Should be used when you need to perform the same task repeatedly
• Is invoked by specifying the function name
• Should be created before invoking it
• The syntax to create a function is:
function <function_name>
{
<commands>
}
Trang 31Creating Functions (Contd.)
• An example of a function is shown below:
function ftype{
if test -f $fnamethen echo "$fname is an ordinary file."
elif test -d $fnamethen echo "$fname is a directory file."
elif test ! -r "$fname"
then echo "No readable file called $fname exists"fi
}echo "Enter a file name"
read fnameftype
• Shell scripting also allows you to pass arguments to function
• The syntax to pass arguments to a function is:
<function name> [ arg1 arg2 ]
Trang 32Debugging Shell Scripts
• Linux facilitates debugging of shell scripts by using the following two options:
• The –v option: Echoes the statements written in a shell script on the
terminal, before actually executing them
• The –x option: Echoes the statements in the script preceded by a +
symbol, if the statement has successfully been executed
• To debug the shell script, you can use the sh <filename> command with
the –v and –x options at the shell prompt:
$ sh –v <filename>
or
$ sh –x <filename>
Trang 33Sample Shell Scripts
Writing a shell script to check whether or not a given string is a
break fi
ctr=`expr $ctr + 1`
len=`expr $len - 1`
done
if test $flag -eq 0
then echo "String is palindrome"
else echo "String not a palindrome"
fi
Trang 34Sample Shell Scripts (Contd.) Writing a shell script to reverse a string:
echo "Enter string"