an introduction to unix shell scripting. unix shells /bin/sh –borne shell /bin/csh – c shell...
Post on 16-Jan-2016
Embed Size (px)
An Introduction to Unix Shell Scripting
UNIX Shells/bin/sh Borne Shell/bin/csh C Shell/bin/ksh Korn Shell/bin/bash Borne Again Shell
Unix Shell ScriptingThe Bourne shell is what we will use for scriptingIt's portableVirtually every Unix system has sh installedIt has a rich set of programming constructsIt is arguable that it is the most popular UNIX shell.
BASH Comments# is the comment symbol in the shell# can occur anywhere on a lineThe shell ignores anything following a # until the end-of-lineOne special exception#! on the first line is used to tell the shell what program to use to interpret the script fileExamples:#!/bin/sh -tells shell to use the Bourne shell to execute the script#!/usr/bin/perl -tells shell to use Perl to execute the script
Shell Outputecho is the primary way to perform output from the shellSyntax: echo [-n] arguments-n - do not append a NEWLINE (suppress the enter)arguments - may be variables or explicit stringsExamplesecho "Hi there, I'm a Unix whiz kid!"echo "My home directory is $HOME"echo $PATHechoTo suppress output from shell commands in a script, redirect the output to /dev/null
Assigning Shell VariablesTo store values in a shell variable, write the name of the variable followed by an = followed by the valuecount=1my_dir=/home/boboNote that spaces are NOT allowed on either side of the =Also, the shell has no concept of data typesNo matter what assignment you make, the shell considers the value as a string of charactersVariables don't need to be declared, they're simply assigned values when you want to use then
Referring to VariablesIn order to refer to the value of a variable, preface the variable name with a $echo $count displays 1echo count displays countecho $my_dir displays /home/boboecho my_dir displays my_dirIf you want to ensure a variable is not accidentally modified, specify it as readonly. Further attempts to modify it will result in an error from the shell.my_dir=/home/boboreadonly my_dir
File Name Substitution & VariablesIf you define a variable as x=* ls $x will produce a directory list of all filesDid the shell store the * in x or the list of files in your current directory?
File Name Substitution & VariablesThe shell stored the * in x, the shell does not perform filename substitution when assigning values to variablesWhat actually happens is:The shell scans ls $x, substituting * for $xIt then rescans the line and substitutes all the files in the current directory for the *
EnvironmentCreate a file called firstscript that contains:#!/bin/bashx=123echo the variable x equals $x
Save it and make it executable (chmod 744 firstscript)
Then execute firstscript - what happens?
Variables in the EnvironmentWhen variables are assigned, they are local to the current shellSince scripts are executed in a sub-shell, these local variables aren't visible to the scriptTo make them visible (inherited by) subsequent sub-shells, they must be exported export my_dirThe env command lists all currently defined exported variables
Advanced echoThe echo command allows for special support of control characters. These special control features include such functions as new line, tab and bell
To Enable the interpretation of special control(escape) characters. One must use the e switch echo e This will \n be on two lines
echo escaped characters \a alert (bell)\b backspace\c suppress trailing newline\f form feed\n new line\r carriage return\t horizontal tab\v vertical tab\\ backslash\nnn The character whose ASCII code is nnn(octal)
Debugging Scripts with -xWhen developing scripts, it is often difficult to debug themIn order to get a trace of what is happening, you can invoke your script by using the shell's -x optionsh -x case.scrThis will trace(show the commands) the statements in the script as they are being executed (similar to leaving echo on in batch files)
Command Line ArgumentsSupposing you ran the scripted called big, using the following command.big red seaYou would be providing your program with two variables. (red and sea)The program can use these variables.
Command Line ArgumentsWhen the shell invokes your script, it assigns the command line arguments to a set of variables$0, $1, $2,$9$0 is the script name$1 is the first argument, $2 the second, up through $9You can then refer to these variables in your script.
What if you have more then 9 command line arguments?If more than 9 arguments are used, you must access them using the shift commandshift simply does a left shift on all the arguments, discarding $1 and making $1 = $2, $2 = $3, etcNote, this means that if you still need $1 you must save it in another variable BEFORE performing the shift
Other Pre-defined Variables$# - number of arguments on command line$* - collectively references all of the positional parameters ($1, $2, $3)$0 - name of program being executed$$ - PID of current process$? - exit status of last command not executed in background
Interactive InputAside from command line arguments input can also be provided by the user as the program in running.to accomplish this simply use the read command
The read CommandSyntax: read var1 var2 var3 Example:read textThis would wait for the user to input a string then the variable text would be set to it.
read gets input from STDIN so it can be redirected from a fileread text < data
QuotingQuotes in shell scripting have special meaning.There are four types of quoting;
Single Quote (next to the enter key) removes the special meaning of all enclosed characters
Double Quote " removes the special meaning of all enclosed characters EXCEPT $, `, and \
Quoting\ removes the special meaning of the character that follows the \; inside double quotes it removes the special meaning of $ ` " NEWLINE and \ but is otherwise not interpreted
Back Quote ` (matilda on the ~ key) executes command inside the quotes and inserts standard output at that point.
Examples of Back Quotingecho Your current directory is `pwd`Outputs "Your current directory is /home/bobo"
echo There are `who | wc -l` users logged onOutputs "There are 13 users logged on"
Single QuotesSince single quotes protect everything, the following output should make sense:echo `who | wc l` tells how many users are logged onOutputs `who -| wc l` tells how many users are logged on
But back quotes are interpreted inside echo "You have `ls | wc -l` files in your directory"Outputs You have 24 files in your directory
Shell ArithmeticThe Bourne shell has no idea how to do arithmeticFor examplenumber=2number=$number + 4echo $number2 + 4That makes shell scripting pretty useless as a programming language doesn't it?
exprFortunately, there is a Unix command that will allow us to perform arithmetic within a scriptThe expr command "evaluates" it's arguments and writes it's output on STDOUTExample:expr 1 + 23expr 6 / 2 + 58
exprNote, since it is evaluating arguments, they must be separated by spacesAlso, expr only works with integer arithmetic expressionsa=1, b=2, c=3expr $a / $b + $c = 3
Make sure not to name your scripts the same as unix commands this may cause yor scripts not to function correctly.The most common mistake is to name your script test