2 UNIX Shells /bin/sh –Borne Shell /bin/csh – C Shell /bin/ksh – Korn Shell/bin/bash Borne Again Shell
3 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.
4 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
5 Shell Output echo is the primary way to perform output from the shell Syntax: 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
6 Assigning Shell Variables To 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
7 Referring to Variables In 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
8 File Name Substitution & Variables If you define a variable as x=*ls $xwill produce a directory list of all filesDid the shell store the * in x or the list of files in your current directory?
9 File Name Substitution & Variables The 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 *
10 Environment Create a file called firstscript that contains: #!/bin/bashx=123echo the variable x equals $xSave it and make it executable (chmod 744 firstscript)Then execute firstscript - what happens?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
11 Variables in the Environment When 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 exportedexport my_dirThe env command lists all currently defined exported variables
12 Advanced echoThe echo command allows for special support of control characters.These special control features include such functions as new line, tab and bellTo Enable the interpretation of special control(escape) characters. One must use the –e switchecho –e “This will \n be on two lines”
13 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)
14 Debugging Scripts with -x When 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)
15 Command Line Arguments Supposing 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.
16 Command Line Arguments When 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.
17 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
18 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
19 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
20 The read Command Syntax: 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
21 Quoting Quotes 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 charactersDouble Quote " removes the special meaning of all enclosed characters EXCEPT $, `, and \
22 Quoting\<character> 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 interpretedBack Quote ` (matilda on the ~ key) executes command inside the quotes and inserts standard output at that point.
23 Examples of Back Quoting echo 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"
24 Single QuotesSince single quotes protect everything, the following output should make sense:echo ‘`who | wc –l` tells how many users are logged on’Outputs `who -| wc –l` tells how many users are logged onBut back quotes are interpreted inside “echo "You have `ls | wc -l` files in your directory"Outputs You have 24 files in your directory
25 Shell Arithmetic The Bourne shell has no idea how to do arithmetic For examplenumber=2number=$number + 4echo $number2 + 4That makes shell scripting pretty useless as a programming language doesn't it?
26 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
27 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