Shell Scripting
Shell Scripting
Shell Scripting
This training is designed to introduce shell utilities, shell scripting and its concepts to users having some experience of working on unix / linux platforms .
Lets begin
% cat > hello.sh #!/bin/sh echo Hello, world ### now we exit exit 0 <ctrl-d> % chmod +x hello.sh % ./hello.sh
% echo $?
3
Filters
Filters
1- Filters take input from the standard i/p files piped o/p 2- Perform an operation on the data . 3- Send the o/p to standard o/p or files .
$>paste tempfile.txt existingfile.txt > see.txt $> cat see.txt This is a temporary file. This is an existing file. Delete it afterwards. $>
$> paste d * tempfile.txt existingfile.txt This is a temporary file.*Delete it afterwards. This is an existing file.* $>
tail :
$> tail myfile.txt $>tail n myfile.txt This displays the last n lines of myfile.txt.
10
11
sort :
sorts alphabetically -n sort numerically -r reverse order -u uniq -t specifies delimeter ( default tab) -k field selection
$> sort fruitsName $> sort u fruitsName $> sort -nr classMarksFile
tr :
translates inputs to output as specified.
$> cat file1.txt | tr [A-Z] [a-z] > file2.txt $> tr [A-Z] [a-z] < file1.txt > file2.txt $> tr aeiou AEIOU < file1.txt > file2.txt
13
14
Regular Expressions
. ^ $ [a-z] a single character start of a line end of a line any single character from a to z
[ab^c] x* xy a
[^a-z]
Supported only by egrep a? a+ a|b (a|b)c zero or one occurrence of a one or more occurrence of a either a or b either ac or bc
16
Grep Family
grep - prints lines that match pattern
grep [ options ] < pattern > < filename >
cmd | grep [ option ] < pattern > Here cmd is any unix command that displays o/p
Options: -n: print line number -v: invert the search criteria -i : makes search criteria case insensitive -c: display only the number of occurence
17
$> cat nf.txt unix is a better OS minix is mini unix in St we have Solaris. ST has developed st pc.
$>grep S[tT] nf.txt in St we have Solaris. ST has developed st pc $>grep nix.*nix nf.txt minix is mini unix
$>grep mi[^ ]*ix nf.txt minix is mini unix $>
20
Shell Variables
21
To use the value of the variable $VAR or ${VAR} example #!/bin/sh COLOR=yellow echo This looks $COLORish echo This seems ${COLOR}ish prints This looks This seems yellowish There is only one type of variable in sh: strings.
22
Environment variables are passed to subprocesses. Local variables are not. By default, variables are local. local variable -> environment variable through export export VAR To unexport a variable unset VAR
23
Shell Meta-Characters
* Matches any string including null string ? [xyz] [a-z] [^xyz] Matches a single character matches x or y or z matches any character from a to z Matches any characters except x, y, z
[^a-z]
24
Usage of Meta-Characters
$>ls file1.txt file2.txt new.txt now.txt $>ls * file1.txt file2.txt new.txt now.txt $>ls file?.txt file1.txt file2.txt $>ls n[a-z]w.* new.txt now.txt
Quoting
Backslash a backslash (``\'') removes any special meaning from the character that follows. echo \wow\ wow Single quotes Single quotes, such as echo '* MAKE $$$ FAST *' * MAKE $$$ FAST *
26
Quoting (cont..)
Double quotes
Double quotes, such as "foo" foo $HOME /home/ramesh
Backquotes
If you have an expression within backquotes (also known as backticks), e.g., `cmd` echo You are `whoami` prints You are ramesh
27
Meaning to shell
redirects the o/p of cmd to file appends the stdout to file redirects stdin from file stdout from cmd1 redirected to stdin of cmd2
cmd1 &
cmd1 ; cmd2 `cmds`
Meaning to shell
executes commands in sub-shell
execute cmds in current shell takes char literally takes string literally Takes string after recognizing $, `cmds` and \
#cmd
Error Handling 0 1 2 cmd >& n cmd <& n cmd 2> file cmd 2>& n cmd 1> file 2>file2 file descriptor for standard input file descriptor for standard output file descriptor for standard error redirects o/p from cmd to fd n redirects i/p from file (fd n) to cmd redirects standard error from cmd to file redirects standard error from cmd to file with fd n redirects standard o/p from cmd to file and standard error to file2
31
$>cat op1
$>expr $y 2> op1
Symbol $n $* $@
Meaning to shell scripts value of nth positional parameter holds all the positional parameters same as $*, but when quoted $* is $1 $2 $3 $4 $5.. but $@ $1 $2 $3 etc. Total no. of positional parameters passed to script excluding $0
$#
$$
$! $$?
Example
$> cat printArguments #!/bin/sh echo "first argument is $1 " echo "second argument is $2 " echo "third argument is $3 " echo "numberof arguments -- $# " echo "all arguments together -- $* " echo "program name is $0 " exit 0 $> chmod 755 printArguments $> printArguments How are you Mr Goblin first argument is How second argument is are third argument is you numberof arguments -- 5 all arguments together -- How are you Mr Goblin program name is printArguments 35
$>script.sh first second third fourth fifth script 5 first second third fourth second third fourth fifth
36
Built-in Functions
exec
- Does not create a child process. - for the new process it keeps the same PID - the current process is terminated with it $> cat testExec.sh
#!/bin/bash exec echo "leaving this script forever $0" # Exit from script here. # ---------------------------------# The following line never happens echo "This echo will never echo.
39
read
- is used to read from the standard input
- if read is used in a shell script, it waits there till input is given by the keyboard.
40
set
43
44
string comparison
test z string - true if length of string is zero test n string - true if length of string is non zero test string1 = string2 - true if string1 is equal to string2
47
File status checking test x file -true if file is executable test file1 nt file2 - true if file1 is newer than file2 test file1 ot file2 - true if file1 is older than file2
52
$> ls dt1 dt2 $>cd dt1 $>ls file1.txt file2.txt $>test f file1.txt $>echo $? 0 $>
53
$>test f file3.txt $>echo $? 1 $>cd ../ $>test f dt1 $>echo $? 1 $>test d dt1 $>echo $? 0 $>
54
58
Matching operator.
Compares the characters in arg1 with the characters in arg2. Returns the number of characters in arg1 matched by characters in arg2. Arg1 should be a string and arg2 should be a regular expression ( with the exception of the ^ character, because all expressions start at the beginning of arg2)
59
$> expr string : '\(.*\)' string $> expr string : '..\(..\)' ri $> expr string : '\(...\)' str $> expr string : '.*\(...\)' ing $> expr string : '\(stx\) $> expr string : 'st\(.*\)' ring
60
Logic: test
test 1 lt 10
[ 1 lt 10 ]
62
Logic: test
[ [ [ [ -f /etc/passwd ] ! f /etc/passwd ] -f /etc/passwd a f /etc/shadow ] -f /etc/passwd o f /etc/shadow ]
63
Flow Constructs
65
66
# see if a file exists if [ -e /etc/passwd ] then echo /etc/passwd exists else echo /etc/passwd not found! fi
68
Multi-way Branching
case
case word in pattern1) commands ;; pattern2 | pattern3) commands ;; *) commands ;; esac
69
for ..
for i in * do echo Listing $i: ls -l $i done
71
Logic: while
while condition do : done
72
Logic: while
a=0; LIMIT=10 while [ "$a" -lt "$LIMIT" ] do echo -n "$a a=`expr $a + 1 ` done
73
Logical Operators
|| and && operator
&& operator can be used to execute a command and if it is successful, execute the next command in the list. cmd1 && cmd2 if cmd1 succeeds, execute cmd2 else nothing
75
|| operator is used to execute a 2nd command if it gets a non zero exit status in the 1st command
cmd1 || cmd2 if cmd1 succeeds, then only cmd1 if cmd1 fails, execute cmd2
76
Function
sh supports a function call in which the value of variables are treated as global The General Syntax is function () { expressions }
77
In the body of shell script, it will be called as function not function() Function should have been defined before being called . Arguments are passed to a function in the same way as passed to a script
78
file descriptors
How to create a file descriptors exec 6</tmp/foo opens the file /tmp/foo for input on the file descriptor #6. This is equivalent to the system call open("/tmp/foo", O_RDONLY) exec 7>/tmp/bar opens the file /tmp/bar for output on the file descriptor #7. If the file already exist it is recreated. This is equivalent to the system call open("/tmp/bar", O_WRONLY|O_CREAT). exec 7>>/tmp/bar opens the file /tmp/bar for appending on the file descriptor #7. If the file does not exist it is created. This is equivalent to the system call open("/tmp/bar", O_APPEND|O_CREAT). exec 6<&close the file descriptor.
79
#!/bin/bash cat /tmp/foo | while read a ; do echo $a >>/tmp/bar done The input file is a file containing 2.000.000 lines. This means that the shell script is going to open, write, and close /tmp/bar 2 million times. Now using the same shell script with file descriptors. #!/bin/bash # open the files exec 6</tmp/foo exec 7>/tmp/bar # data "processing" cat <&6 | while read a ; do echo $a >&7 done exec 6&exec 7&the performance increase to almost 4.5.
80
SED
81
works line by line throws the o/p on console the original file is left unchanged.
82
sed
The syntax for the utility is: sed [options] '{command} [filename]
83
84
er1 file1.txt
file2.txt $>sed /n[a-z]w/q op1 er1 file1.txt file2.txt new.txt $>sed n $p op1 op1 $>
sed n m, np file
- prints m to n lines of the file
$>sed n /file/p op1 file1.txt file2.txt $>sed n /file/,/n[a-z]w/p op1 file1.txt file2.txt new.txt
87
88
globally
89
/./
/^$/ /st/ /^st/ /st$/ /^st$/ /^st.$/ /st\.$/
matches in sed
st or St anywhere in the line st followed by a digit st followed by a non-digit st followed by a digit and then followed by a non digit sgs followed by any string and then by st
/sgs.*st/
/sgs.*st$/
sgs followed by any string and then by st at the end of the line
/\/st\//
References The ampersand (&) holds the matched string: $> sed 's/[aeiou]/&&/g'
94
Referencing a substring Substrings enclosed with "\(" and "\)" can be referenced with "\n" (n is a digit from 1 to 9) $> sed 's/^\(\).*\(\)$/\2:\1/'
95
awk
awk runs through a text file. awk reads and process one record at a time. each field is separated by a variable FS
96
awk
General syntax of awk is
awk BEGIN { ##begin section (optional ) } { ### main section } END { ### end section (optional) } filename
97
Features
inbuilt variables
inbuilt functions flow control
hash tables
98
ORS
$0 $n
entire input record nth field of current record, the fields are separated by FS
99
x++
x-x += y
increments x by 1
decrements by 1 x=x+y
x -= y
x=x-y
100
int(x)
rand cos(x) sin(x) atan2(x, y) exp(x) log(x)
truncates x to a whole no
a random no. between 0 and 1 cosine of x sine of x arc tangent of y/x e raised to the power of x logarithm of x
sqrt(x)
Example
$>cat op1 er file1.txt file3.txt now.txt File4.txt new.txt
Example
$>awk /[Ff]ile/ {print $0} op1 file1.txt file3.txt now.txt File4.txt $>
103
Example
$>cat pr.txt main 20 printf:pow sort 120 return:log max 40 swap:return $>awk {print $2, $1} pr.txt 20 main 120 sort 40 max $>
104
Example
$>cat pr.txt main 20 printf:pow sort 120 return:log max 40 swap:return
$>awk F: { print $1 } pr.txt main 20 printf sort 120 return max 40 swap
105
BEGIN
- In awk begin and end are two keywords. BEGIN{actions} perform the actions before reading any record - BEGIN is mainly used to initialize some variables e.g. FS
END - Similarly END{actions} perform the actions after all record has been processed - END is normally used to calculate some end result e.g. calculating average
106
108
if constructs in awk
awk flow construct if has following syntax
if ( condition1 )
110
ARRAYS
ASSOCIATIVE ARRAYS ARRAY_NAME[key]=value
To iterate through the keys for (keyName in ARRAY_NAME ) { print key "--" ARRAY_NAME [keyName] }
111
$>cat questions where are you? why are you here? Can you lend me 1000 Rs ? $>awk BEGIN { ARRAY["where are you?"]="NOIDA"; ARRAY["why are you here?"]="had nothing else to do }{ if(ARRAY[$0]=="") { value="sorry ! I didnt get the question } else { value=ARRAY[$0]; } print $0"\t\n\t"value }' questions where are you? NOIDA why are you here? had nothing else to do Can you lend me 1000 Rs ? sorry ! I didnt get the question
112
113
x~y
x !~ y && || !(x = y)
length(str)
- returns the length of the string
115
116