The document discusses the UNIX file system, including directories, file types, and important directories. It describes the hierarchical structure of directories with the root directory at the top, and subdirectories branching below. It defines regular files, directory files, and special files. It also outlines some important standard directories like /usr, /usr/docs, and users' home directories.
2. *
* of 70
UNDERSTANDING UNIX SHELL PROGRAMMING
LANGUAGE: AN INTRODUCTIONA command language –
interpreted (not compiled)Shell program files are called shell
procedures, shell scripts, or simply scriptsA file that contains a
series of commands for the shell to execute
* of 70
Writing a Simple Script
* of 70
Executing a Script
Making Files Executable: The chmod Command
* of 70
Executing a Script
Making Files Executable: The chmod Command
* of 70
Executing a Script
Making Files Executable: The chmod Command
5. specified
$echo –e “HnEnLnLnO”
* of 70
WRITING MORE SHELL SCRIPTSLogging Off in Style
* of 70
WRITING MORE SHELL SCRIPTSExecuting Commands: The
dot CommandLets you execute a program in the current shell
and prevents the shell from creating the child process
* of 70
WRITING MORE SHELL SCRIPTSPath Modification
Command SubstitutionPlace the output of a command in the
argument string
* of 70
WRITING MORE SHELL SCRIPTSReading Inputs: The read
Command
* of 70
Reading Inputs: The read Command
Amir Afzal
8. EXPLORING THE SHELL: PROGRAMMING
BASICSTerminating Programs: The exit CommandUse to
immediately terminate execution of your shell program
Conditions and TestsThe if-then construct
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSThe if-
then-else Construct
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSThe if-
then-else Construct
no #
Notice the spaces before and after
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSThe if-
then-elif Construct
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSThe if-
then-elif Construct
hour= `date +%H’
Replace these
two lines (8 and 9)
9. * of 70
EXPLORING THE SHELL: PROGRAMMING BASICSThe if-
then-elif Construct
if [ “$answer” = Y ]
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSTesting
Different CategoriesNumeric Valuesuse the test command to
test (compare) two integer numbers algebraically
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSScenario
– write a script that:Accepts three numbers as input (command
line arguments) and … Displays the largest of the threeOutput
should look like this:
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICS
if [ “$num1” –gt “$num2” -a “$num1” –gt “$num3” ]
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSString
ValuesCompare (test) strings with the test command
* of 70
10. EXPLORING THE SHELL: PROGRAMMING BASICSString
ValuesCompare (test) strings with the test command
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSFiles –
use the test command to test file characteristicsSize, type,
permissions
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSFiles –
use the test command to test file characteristicsSize, type,
permissions
if [ -r “$FILE” ]
* of 70
EXPLORING THE SHELL: PROGRAMMING BASICSFiles –
use the test command to test file characteristics
* of 70
EXPLORING THE SHELL: PROGRAMMING
BASICSParameter SubstitutionLets you test the value of a
parameter and change its value according to a specified option
If variable has value
return this value
Else
return the string
If variable has value
11. return the string
Else
nothing
If variable has value
return this value
Else
variable = string
If variable has value
return this value
Else
print string
* of 70
echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"
echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var“
var="Prefix"
echo ${var:+"This is default value"}
12. echo "4 - Value of var is $var"
echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"
Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix
* of 70
EXPLORING THE SHELL: PROGRAMMING
BASICSParameter Substitution
Notice the exit from the script
If name is still empty
* of 70
EXPLORING THE SHELL: PROGRAMMING
BASICSParameter Substitution
* of 70
13. ARITHMETIC OPERATIONSThe expr Command – Arithmetic
OperatorsNote: spaces between the elements of an expression
are necessary, integer only
* of 70
ARITHMETIC OPERATIONSThe expr Command – Arithmetic
Operators
The * (multiplication) and % (remainder) characters have
special meaning to the shell, they must be preceded by a
backslash []
* of 70
ARITHMETIC OPERATIONSThe expr Command – Arithmetic
Operators
The grave accent marks [` and `] surrounding the command are
necessary and cause the output of the command (expr) to be
substituted.
$ x=10
$ y=20
$ z=`expr $x + $y`
* of 70
$ c=`expr $a + $b`
$ echo “the value of addition=$c”
$ d=`expr $a - $b`
$ echo “the value of subtraction=$d”
$ e=`expr $a * $b`
14. $ echo “the value of multiplication=$e”
$ f=`expr $a / $b`
$ echo “the value of division=$f”
$ g=`expr $a % $b`
$ echo “the value of modulus=$g”
Show the output of each code segment?
* of 70
ARITHMETIC OPERATIONSRelational OperatorsRelational
operators that work on both numeric and nonnumeric
arguments.If both arguments are numeric, the comparison is
numericIf one or both arguments are nonnumeric, the
comparison is nonnumeric and uses the ASCII values.because >
(greater than) and < (less than) characters have special meaning
to the shell, they must be preceded by a backslash []
n1=10
n2=20
if [ “$n1” > “$n2” ]
then
echo “$n1 is greater than $n2”
else
echo ”$n1 is not greater than $n2”
fi
* of 70
ARITHMETIC OPERATIONSArithmetic Operations: The let
CommandSimpler alternative to the expr command and includes
all the basic arithmetic operations
15. * of 70
THE LOOP CONSTRUCTSThe For Loop: The for-in-done
ConstructUsed to execute a set of commands a specified number
of times
* of 70
THE LOOP CONSTRUCTSThe For Loop: The for-in-done
Construct
* of 70
for var in "[email protected]"
do
echo "$var"
done
for i in {1..5}
do
echo "Welcome $i times"
done
for num in `seq 1 2 10`
do
echo "$num"
done
* of 70
for (( c=1; c<=5; c++ ))
16. do
echo "Welcome $c times"
done
exit 0
Spaces are not important here
* of 70
THE LOOP CONSTRUCTSThe For Loop: The for-in-done
Construct
* of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
ConstructThe while loop continues as long as the loop condition
is true.
* of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
Construct
* of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
ConstructCommand line version of the carryon program
* of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
Construct
17. * of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
Construct
* of 70
THE LOOP CONSTRUCTSThe While Loop: The while-do-done
Construct
* of 70
THE LOOP CONSTRUCTSThe Until Loop: The until-do-done
ConstructSimilar to the while loop, except … It continues
executing the body of the loop as long as the condition of the
loop is falseBody of the until loop might never get executed if
the loop condition is true
* of 70
THE LOOP CONSTRUCTSScenario: check whether a specified
user is on the system or, if not, to be informed as soon as the
user logs in
* of 70
DEBUGGING SHELL PROGRAMSThe Shell CommandUse the
sh, ksh, or bash command with one of its options to make the
debugging of your script files easierOptions
53. ARRAYSArray is a variable which contains multiple values
may be of same type or different type since by default in shell
script everything is treated as a string. An array is zero-based ie
indexing start with 0.
*
HOW TO DECLARE ARRAY IN SHELL SCRIPTING?
1. Indirect Declaration
Assign a value in a particular index of Array Variable. No need
to first declare
ARRAYNAME[INDEXNR]=value
2. Explicit Declaration
declare -a ARRAYNAME
3. Compound Assignment
ARRAYNAME=(value1 value2 .... valueN)
*
ARRAYS IN BASHbash has two types of arrays: one-
dimensional indexed arrays and associative arrays • Any
variable can be used as a 1D array – Identified as var[index]
$x=24
$ echo ${x[0]}Indexed arrays
• Index array need not be declared though they can be using
the command declare -a
• You can also declare arrays of any size by
declare -a color[3]
with the elements indexed from 0 to 2 –
In reality, the index above is ignored
54. – You can simply add more elements to it by assigning an
element with a new index
*
ACCESSED BY AN INDEX
– Index starts at 0
– Index can be any positive integer, up to 599147937791
– Arithmetic expressions are supported in index
• Values are assigned by
var[index]=value
• Examples
color[1]="red"
color[2]="green"
color[0]="blue"
– Values need not be assigned in any specific order
Another way to assign values, known as compound statement, is
color=([2]=green [1]=red [0]=blue)
*
If you specify the elements in order, you can specify them as
color=(red blue green)
• The above values can be accessed by
for i in 0 1 2
do
echo ${color[$i]}
done
– You must use the curly braces to access array elements;
otherwise, you’ll just get the first array element and the
subscript
56. TO COUNT LENGTH OF ARRAY
*
COLOR=(RED BLUE GREEN)
*
COLOR=(RED BLUE GREEN)
*
COLOR=(RED BLUE GREEN)
*
The contents of the colors array is not change, only the output
*
BASH ASSOCIATIVE ARRAY EXAMPLES
*
*
(foo=bar baz=quux corge=grault)
58. *
*
ECHO
*
*
${MYMAP[${KEYS[$I]}]}
KEYS=(“foo a” “baz b)
SCOPE
*
ARRAYSArray is a variable which contains multiple values
may be of same type or different type since by default in shell
script everything is treated as a string. An array is zero-based ie
59. indexing start with 0.
*
HOW TO DECLARE ARRAY IN SHELL SCRIPTING?
1. Indirect Declaration
Assign a value in a particular index of Array Variable. No need
to first declare
ARRAYNAME[INDEXNR]=value
2. Explicit Declaration
declare -a ARRAYNAME
3. Compound Assignment
ARRAYNAME=(value1 value2 .... valueN)
*
ARRAYS IN BASHbash has two types of arrays: one-
dimensional indexed arrays and associative arrays • Any
variable can be used as a 1D array – Identified as var[index]
$x=24
$ echo ${x[0]}Indexed arrays
• Index array need not be declared though they can be using
the command declare -a
• You can also declare arrays of any size by
declare -a color[3]
with the elements indexed from 0 to 2 –
In reality, the index above is ignored
– You can simply add more elements to it by assigning an
element with a new index
*
60. ACCESSED BY AN INDEX
– Index starts at 0
– Index can be any positive integer, up to 599147937791
– Arithmetic expressions are supported in index
• Values are assigned by
var[index]=value
• Examples
color[1]="red"
color[2]="green"
color[0]="blue"
– Values need not be assigned in any specific order
Another way to assign values, known as compound statement, is
color=([2]=green [1]=red [0]=blue)
*
If you specify the elements in order, you can specify them as
color=(red blue green)
• The above values can be accessed by
for i in 0 1 2
do
echo ${color[$i]}
done
– You must use the curly braces to access array elements;
otherwise, you’ll just get the first array element and the
subscript
*
62. *
COLOR=(RED BLUE GREEN)
*
COLOR=(RED BLUE GREEN)
*
COLOR=(RED BLUE GREEN)
*
The contents of the colors array is not change, only the output
*
BASH ASSOCIATIVE ARRAY EXAMPLES
*
*
(foo=bar baz=quux corge=grault)
64. *
*
ECHO
*
*
${MYMAP[${KEYS[$I]}]}
KEYS=(“foo a” “baz b)
SCOPE
*
* of 44
*created by: Aho, Weinberger, and Kernighanscripting language
used for manipulating data and generating reportsversions of
awkawk, nawk, mawk, pgawk, … GNU awk: gawk
65. * of 44
What can you do with awk?awk operation:scans a file line by
line splits each input line into fieldscompares input line/fields
to patternperforms action(s) on matched linesUseful
for:transform data filesproduce formatted reportsProgramming
constructs:format output linesarithmetic and string
operationsconditionals and loops
*
* of 44
The Command: awk
*
* of 44
Simple awk commandawk ‘Pattern { Command }’ inputFile
$ cat textfile
Line number 1
Line number 2
Line number 3
Line number 4
Line number 5
$ awk ‘/4/ {print }’ textfile
Line number 4
condition
action
66. * of 44
Basic awk Syntaxawk [options] ‘script’ file(s)
$ awk ‘/4/ {print }’ textfile
awk [options] –f scriptfile file(s)
Options:
-F to change input field separator
-F: or -F,
-f to name script file
Since awk itself can be a complex language, you can store all
the commands in a file and run it with the –f flag
*
The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
Basic awk Programconsists of patterns & actions:
pattern {action}
if pattern is missing, action is applied to all linesif action is
missing, the matched line is printedmust have either pattern or
action
67. Example:
$ awk '/for/' testfile prints all lines containing string “for” in
testfile
$ awk ‘{print }’ testfile
- print all lines in testfile
*
The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
Basic Terminology: input fileA field is a unit of data in a
lineEach field is separated from the other fields by the field
separatordefault field separator is whitespaceA record is the
collection of fields in a lineA data file is made up of records
*
Example Input File
The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
68. Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
Buffersawk supports two types of buffers:
record and field
field buffer:one for each fields in the current record.names: $1,
$2, …
record buffer :$0 holds the entire current record
*
* of 44
Some System Variables
FS Field separator (default=whitespace)
RS Record separator (default=n)
NF Number of fields in current record
NR Number of the current record
OFS Output field separator (default=space)
ORS Output record separator (default=n)
FILENAME Current filename
*
* of 44
69. Example: Records and Fields
$ cat emps
Tom Jones 4424 5/12/66 543354
Mary Adams 5346 11/4/63 28765
Sally Chang 1654 7/22/54 650000
Billy Black 1683 9/23/44 336500
$ awk '{print NR, $0}' emps
1 Tom Jones 4424 5/12/66 543354
2 Mary Adams 5346 11/4/63 28765
3 Sally Chang 1654 7/22/54 650000
4 Billy Black 1683 9/23/44 336500
*
No pattern, just action
on each record (line)
The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
Example: Space as Field Separator
$ cat emps
Tom Jones 4424 5/12/66 543354
Mary Adams 5346 11/4/63 28765
Sally Chang 1654 7/22/54 650000
Billy Black 1683 9/23/44 336500
70. $ awk '{print NR, $1, $2, $5}' emps
1 Tom Jones 543354
2 Mary Adams 28765
3 Sally Chang 650000
4 Billy Black 336500
*
No pattern, just action
on each record (line)
The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
Example: Colon as Field Separator
$ cat em2
Tom Jones:4424:5/12/66:543354
Mary Adams:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
Billy Black:1683:9/23/44:336500
$ awk -F: '/Jones/{print $1, $2}' em2
Tom Jones 4424
*
Pattern and action
on each record (line)
71. The AWK/NAWK Utility
The AWK/NAWK Utility
Copyright Department of Computer Science, Northern Illinois
University, 2004
*
Copyright Department of Computer Science, Northern Illinois
University, 2004
* of 44
BEGIN And END BlocksTwo special patterns that can be
matchedBEGINCommands are executed before any records are
looked atENDCommands are executed after all records are
processed
* of 44
Example
$cat textfile
Line number 1
Line number 2
Line number 3
Line number 4
Line number 5
$ awk '/4/ {print $0} BEGIN {print "hello"} END {print
"goodbye"}' textfile
Hello
Line number 4
72. goodbye
$
Step 1
Step 2
Step 3
* of 44
$ ls | awk ' BEGIN {print "List of html files:" } /.html$/
{print} END { print "There you go !" }'
List of html files:
as1.html
as2.html
index.html
There you go !
* of 44
Awk Patterns/regular expression/ Relational expression>, <, >=,
<=, ==Pattern && patternPattern || patternPattern1 ? Pattern2 :
pattern3If Pattern1 is True, then Pattern2, else pattern
3(pattern)! Pattern
* of 44
Example Patterns
$ cat textfile2
Just a text file Nothing to see here
Some lines have
More fields than others
73. And some
Are blank
$ awk 'NF > 3 {print $0}' textfile2
Just a text file Nothing to see here
More fields than others
$ awk 'NF > 3 || /^$/ {print $0}' textfile2
Just a text file Nothing to see here
More fields than others
$ awk 'NF > 3 ? /file/ : /^And/ {print $0}' textfile2
Just a text file Nothing to see here
And some
* of 44
Awk ActionsEnclosed in { }() Grouping$ Field reference++ --
Increment, decrement^ Exponentiation+ - ! Plus, minus, not* /
% Multiplication, division, and modulus
* of 44
*
* of 44
74. *
$ awk '{print $1, $2 * $3}' empsrh
John 325
Smith 420
Tom 117
George 756
Sam 132
$cat empsrh
John 13 25
Smith 14 30
Tom 9 13
George 21 36
Sam 11 12
* of 44
*
$ awk '{print "total pay for", $1, " is ", $2 * $3}' empsrh
total pay for John is 325
total pay for Smith is 420
total pay for Tom is 117
total pay for George is 756
total pay for Sam is 132
$ cat empsrh
John 13 25
Smith 14 30
Tom 9 13
George 21 36
Sam 11 12
75. * of 44
*
* of 44
*
* of 44
Example: Computing with awk
$cat empsrh
John 13 25
Smith 14 30
Tom 9 13
George 21 36
Sam 11 12
$ awk '$3 > 15 {emp = emp +1} END {print emp, “employees
worked more than 15 hours"}' empsrh
3 employees worked more than 15 housr
* of 44
76. Example: Computing with awk
$cat empsrh
John 13 25
Smith 14 30
Tom 9 13
George 21 36
Sam 11 12
$awk '{pay = pay + $2 * $3} END {print NR, "employees";
print "total pay is", pay; print "average pay is", pay/NR}'
empsrh
5 employees
total pay is 1750
average pay is 350
* of 44
*
$ awk '$2 > maxrate {maxrate = $2; maxemp =$1}
END {print "Highest rate is:", maxrate, "for", maxemp}’
emprate
* of 44
awk
$ cat em2
Tom Jones:4424: 5/12/66:543354
Mary Adam:5346:11/4/63:28765
Sally Chang:1654:7/22/54:650000
77. Billy Black:1683:9/23/44:336500
$ awk -F: '{names=names $1 " "} END {print names}' em2
Tom Jones Mary Adam Sally Chang Billy Black
*
* of 44
Example: I want to go through and calculate the average score
on the Midterm
$ cat grades
Jason William:Midterm:100
Jane Smith:Quiz 1:45
Tom Ram:Final:78
Sarah George:Midterm:23
Franklin Rob:Midterm:46
$ awk -F: '/Midterm/ {count++; sum= sum + $3}
BEGIN {count=0 ; sum=0} END {print sum/count}' grades
56.3333
$
* of 44
Another Example
Adding 12 points to everyone’s midterm score
$ cat grades
Jason William:Midterm:100
Jane Smith:Quiz 1:45
Tom Ram:Final:78
Sarah George:Midterm:23
Franklin Rob:Midterm:46
$awk -F: '/Midterm/ {$3 =$3 + 12; print $0} /Quiz/ || /Final/
{print $0}' grades
78. Jason William Midterm 112
Jane Smith:Quiz 1:45
Tom Ram:Final:78
Sarah George Midterm 35
Franklin Rob Midterm 58
* of 44
Example
$ colors=(red blue orange green purple)
$ echo ${colors[@]} | awk '{for (i=NF; i > 0; --i) print $i}’
purple
green
orange
blue
red
* of 44
awk Versus bash $ argumentsAlways enclose everything to awk
in single quotes
$1 to awk means something completely different than $1 to
bash$1 in awk means first field$1 in bash means first command
line argument
* of 44
79. User Defined Variables
Variable names could be anything, but it can’t begin with a
number.
You can assign a variable as in shell scripting like this:
$ cat script0
BEGIN {
test="This is a test"
print test
}
$ awk -f script0
This is a test
* of 44
Example: script in a file
$ cat testfile
{print $1 "home at " $6}
$ awk -F: -f testfile /etc/passwd
kuskarhome at /home/STUDENTS/majors/kuskar
juswstahome at /home/STUDENTS/majors/juswsta
dusgmoohome at /home/STUDENTS/nonmajors/dusgmoo
jerpcamhome at /home/STUDENTS/majors/jerpcam
pralam6home at /home/STUDENTS/majors/pralam6
jonnrob1home at /home/STUDENTS/majors/jonnrob1
….
$ cat testfile2
{
text = $1 "home at " $6
print text
}
81. sys /dev
sync /bin
games /usr/games
$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
* of 44
Sometimes, the fields are distributed without a fixed separator.
In these cases, FIELDWIDTHS variable solves the problem.
$ cat testfile4
1235.96521
927-8.3652
36257.8157
$awk 'BEGIN {FIELDWIDTHS="3 4 3"}{print $1, $2, $3}'
testfile4
123 5.96 521
927 -8.3 652
362 57.8 157
* of 44
82. Suppose that your data are distributed on different lines
$ cat testfile5
Jalal Omer
123 High Street
(222) 466-1234
James Smith
456 High Street
(333) 456-7890
$ awk 'BEGIN {FS="n"; RS=""} {print $1," ", $2," ", $3}'
testfile5
Jalal Omer 123 High Street (222) 466-1234
James Smith 456 High Street (333) 456-7890
* of 44
$ cat testfile6
{
if ($1 > 30)
{
x = $1 * 3
print x
}
else
{
x = $1 / 2
print x
}
}
$ awk -f testfile6 numbers
5
83. 7.5
3
99
135
10
4
11
$ cat numbers
10
15
6
33
45
20
8
22
* of 44
While Loop
You can use the while loop to iterate over data with a condition.
$ cat testfile7
{
sum = 0
i = 1
while (i < 4)
{
sum += $i
i++
}
average = sum / 3
print "Average: ", average
84. }
$ awk -f testfile7 nums
Average: 127
Average: 129.667
Average: 192.667
Average: 165.333
$ cat nums
124 127 130
112 142 135
175 158 245
118 231 147
For each input line do
From here
To
Here
* of 44
You can exit the loop using break command like this:
$ cat testfile8
{
sum = 0
i = 1
while (i < 4)
{
sum += $i
i++
if (i == 3)
break
}
average = sum / 3
print "Average: ", average
}
[email protected]:~$ awk -f testfile8 nums
85. Average: 83.6667
Average: 84.6667
Average: 111
Average: 116.333
$ cat nums
124 127 130
112 142 135
175 158 245
118 231 147
Wrong averages.
Why?
* of 44
The for Loop
$ cat testfile9
{
sum = 0
for (i =1; i < 4; i++)
{
sum += $i
}
average = sum / 3
print "Average: ", average
}
[email protected]:~$ awk -f testfile9 nums
Average: 127
Average: 129.667
Average: 192.667
Average: 165.333
$ cat nums
124 127 130
112 142 135
86. 175 158 245
118 231 147
* of 44
Mathematical Functions
sin(x) cos(x) sqrt(x) exp(x) log(x) rand()
$ awk 'BEGIN{x=rand(); y= sqrt(16); print x, y}'
0.237788 4
String Functions
$ awk 'BEGIN{x="likegeeks"; print toupper(x)}'
LIKEGEEKS
* of 44
User Defined Functions
$ cat testfile10
function myfunc()
{
printf "The user %s has home path at %s n", $1, $6
}
BEGIN {FS=":"}
{
myfunc()
}
$ awk -f testfile10 /etc/passwd
The user root has home path at /root
The user daemon has home path at /usr/sbin
The user bin has home path at /bin
87. The user sys has home path at /dev
The user sync has home path at /bin
The user games has home path at /usr/games
For each input line do
Call this function
$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
* of 44
Awk Text Split into an array
$ echo "12 23 11" | awk '{split($0, a); print a[3], a[2], a[1]}'
11 23 12
$ echo "12,23,11" | awk '{split($0, a,","); print a[3], a[2], a[1]}'
11 23 12
$ awk ‘{split($0, arr, “:”), print arr[4], arr[1]}’ inputfile
* of 44
$ cat file1
108. Files - The OS makes it easy for you to organize your computer.
Through the OS you are able to do a number of things to data,
including copy, move, delete, and rename it. This makes it much
easier to find and organize what you have.
*
*
*
Operating System FunctionsInitialize computer
hardwareAllocate system resources to programs Keep track of
multiple programs running at same timeProvide organized
method for all programs to use system devices
UNIX Structure
Introduction to Linux
*
*
Structure
109. *
Parts of the UNIX OSThe Kernel - handles memory
management, input and output requests, and program
scheduling. Technically speaking, the kernel is the OS. It
provides the basic software connection to the hardware.
The Shell and Graphical User Interfaces (GUIs) - basic UNIX
shells provides a “command line” interface which allows the
user to type in commands. These commands are translated by
the shell into something the kernel can comprehend, and then
executed by the kernel.
The Built-in System Utilities - are programs that allow a user to
perform tasks which involve complex actions. Utilities provide
user interface functions that are basic to an operating system,
but which are too complex to be built into the shell. Examples
of utilities are programs that let us see the contents of a
directory, move & copy files, remove files, etc...
Application Software & Utilities – these are not part of the
operating system, per se. They are additional programs that are
bundled with the OS distribution, or available separately. These
can range from additional or different versions of basic utilities,
to full scale commercial applications.
*
*
UNIX
110. Unix is a multi-user, multi-tasking operating system.
You can have many users logged into a system simultaneously,
each running many programs.
It's the kernel's job to keep each process and user separate and
to regulate access to system hardware, including cpu, memory,
disk and other I/O devices.
*
*
General Characteristics of UNIX as an Operating System
(OS)Multi-user & Multi-tasking - most versions of UNIX are
capable of allowing multiple users to log onto the system, and
have each run multiple tasks. This is standard for most modern
OSs. Over 40 Years Old - UNIX is over 40 years old and it's
popularity and use is still high. Over these years, many
variations have spawned off and many have died off, but most
modern UNIX systems can be traced back to the original
versions. It has endured the test of time. For reference,
Windows at best is half as old (Windows 1.0 was released in the
mid 80s, but it was not stable or very complete until the 3.x
family, which was released in the early 90s). Large Number of
Applications – there are an enormous amount of applications
available for UNIX operating systems. They range from
commercial applications such as CAD, Maya, WordPerfect, to
many free applications. Free Applications and Even a Free
Operating System - of all of the applications available under
UNIX, many of them are free. The compilers and interpreters
that we use in most of the programming can be downloaded free
of charge. Less Resource Intensive - in general, most UNIX
111. installations tend to be much less demanding on system
resources. In many cases, the old family computer that can
barely run Windows is more than sufficient to run the latest
version of Linux. Internet Development - Much of the backbone
of the Internet is run by UNIX servers. Many of the more
general web servers run UNIX with the Apache web server -
another free application.
*
*
History of UNIX
First Version was created in Bell Labs in 1969.
Some of the Bell Labs programmers who had worked on this
project, Ken Thompson, Dennis Ritchie, Rudd Canaday, and
Doug McIlroy designed and implemented the first version of the
Unix File System on a PDP-7 along with a few utilities. It was
given the name UNIX by Brian Kernighan.
00:00:00 Hours, Jan 1, 1970 is time zero for UNIX. It is also
called as epoch.
*
*
112. History of UNIX
1973 Unix is re-written mostly in C, a new language developed
by Dennis Ritchie.
Being written in this high-level language greatly decreased the
effort needed to port it to new machines.
*
*
History of UNIX
Introduction to Linux
1977 There were about 500 Unix sites world-wide.
1980 BSD 4.1 (Berkeley Software Development)
1983 SunOS, BSD 4.2, System V
1988 AT&T and Sun Microsystems jointly develop System V
Release 4 (SVR4). This later developed into UnixWare and
Solaris 2.
1991 Linux was originated.
An interesting and rather up-to-date timeline of these variations
of UNIX can be found at
http://www.levenez.com/unix/history.html.
113. *
*
Flavors of UNIXThese can be grouped into two categories:
Open Source and TrademarkedTrademarked : (redistribution
and modification prohibited or restricted; not free)Solaris .
IRIXMac OS X . and many others... Open Source: (source code
is readily available and free to modify)FreeBSDLinux
Distributions:RedHat and the Fedora Project (maintained by
RedHat)MandrakeDebianSuSESlackwareUbuntuand many
others...As a side note, Linux is a open source UNIX-based OS
that was originally developed in 1991 by Linus Torvalds, a
Finnish undergraduate student.
*
*
What is Linux?A clone of UnixDeveloped in 1991 by Linus
Torvalds, a Finnish graduate studentInspired by and
replacement of Minix
Minix was a mini-OS originally developed by Andrew
Tanenbaum to teach of the fundamentals of operating system
design Linus' Minix became LinuxConsist ofLinux KernelGNU
(GNU is Not Unix) Software
differs from Unix by being free software and containing no
Unix code.Software Package management
*
114. The GNU Linux project was created for the development of
a Unix-like operating system that comes with source code that
can be copied, modified, and redistributed
What is LINUX
Introduction to Linux
Linux is a free Unix-type operating system originally created by
Linus Torvalds with the assistance of developers around the
world.
The Kernel version 1.0 was released in 1994 and today the most
recent stable version is 2.6.9
Developed under the GNU General Public License , the source
code for Linux is freely available to everyone.
*
*
What is Linux?Originally developed for 32-bit x86-based
PCPorted to other architectures, eg.Alpha, VAX, PowerPC, IBM
S/390, MIPS, IA-64PS2, TiVo, cellphones, watches, Nokia
N810, NDS, routers, NAS, GPS, …
*
115. Which Linux Distribution is better?> 300 Linux
DistributionsSlackware (one of the oldest, simple and stable
distro.)RedhatRHEL (commercially support)Fedora
(free)CentOS (free RHEL, based in England)SuSe ( based in
German)Gentoo (Source code based)Debian (one of the few
called GNU/Linux)Ubuntu (based in South Africa)Knoppix
(first LiveCD distro.)…
*
*
The Free Software Foundation
and the GNU ProjectFree software foundation (FSF)Software
itself should not be restricted in distribution by standard
commercial license agreementGNU projectCompletely free
version of UNIXWritten from scratch
*
The Free Software Foundation and the GNU Project
(continued)Software licenseLegal definition of who can use
software and how it can be usedGNU general public license
(GPL) Very different from standard commercial software
licenseAuthor agrees to give away source codeAnyone is
licensed to redistribute it in any form
*
Linux ArrivesLinus TorvaldsDecided to create UNIX-like
operating system kernel for IBM-compatible PCSolicited help
via InternetReleased Linux kernel under GPLLinux development
methodPerson identifies need and begins writing
116. programDeveloper announces project on Internet
*
Linux Arrives (continued)Linux development method
(continued)Others respond and work on different parts of
projectPerson leading project releases softwarePeople download
source code and try program; send back information about
problems Developers fix bugsForkingCreating new project
based on existing source code
*
Motivating Free Software DevelopersWhy would so many
people devote so much effort to something without expecting
any reward?Fills developer’s specific technical needRespect of
like-minded professionalsSense of contribution and
communityValuable boost to developer’s resume
*
The Strengths Of
LinuxStabilitySecuritySpeedCostMultiprocessing and other
high-end featuresApplications
*
Hardware RequirementsCan run on very minimal
hardwareRecommend that computer have minimum of:1 GB of
free disk space 64 MB of RAMFor Red Hat Enterprise Linux
installations:256 MB of RAM300 MHZ CPU800 MB of free
disk space
117. *
Version NumberingVersion numbers assigned to:Each release of
Linux kernel Each component of Linux distribution Linux
distributionsMost users select latest available version
*
Linux CertificationIndustry certification programsRed Hat
Certified TechnicianRed Hat Certified EngineerLPI
Certification (Linux Professional Institute)Linux Certified
Administrator (LCA) CertificationLinux+ CertificationNovell
Certified Linux Engineer
*
Linux Certification (continued)Red Hat’s certification
programVery highly regardedTraining program consists of three
courses
*
The Work of a System AdministratorLinux is increasingly part
of information technology infrastructure of large
organizationsKnowledge of Linux can set you on path to a
fulfilling and profitable career
*
Careers in LinuxSystem administrator Network administrator
118. Software engineerTrainer Technical writer Product marketing
Business consultant
ECU CS server Unix version
[email protected]:~$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/term
s-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
*
BASH SHELL PROGRAMMINGInputprompting usercommand
line argumentsDecision:if-then-elsecaseRepetitiondo-while,
repeat-untilforselectFunctionsTraps
*
USER INPUTshell allows to prompt for user input
Syntax:
119. read varname [more vars]
or
read –p "prompt" varname [more vars]
words entered by user are assigned to
varname and “more vars”last variable gets rest of input
line
*
USER INPUT EXAMPLE
#! /bin/sh
read -p "enter your name: " first last
echo "First name: $first"
echo "Last name: $last"
*
BASH CONTROL STRUCTURESif-then-
elsecaseloopsforwhileuntilselect
*
RELATIONAL OPERATORS
*MeaningNumericStringGreater than-gtGreater than or equal-
geLess than-ltLess than or equal-leEqual-eg= or ==Not equal-
ne!=str1 is less than str2str1 < str2str1 is greater str2str1 >
str2String length is greater than zero-n strString length is zero-z
str
120. COMPOUND LOGICAL EXPRESSIONS
! not
&& and
|| or
*
and, or
must be enclosed within
[[ ]]
EXAMPLE: USING THE ! OPERATOR
#!/bin/bash
read -p "Enter years of work: " Years
if [ ! "$Years" -lt 20 ]; then
121. echo "You can retire now."
else
echo "You need 20+ years to retire"
fi
*
EXAMPLE: USING THE && OPERATOR
#!/bin/bash
Bonus=500
read -p "Enter Status: " Status
read -p "Enter Shift: " Shift
if [[ "$Status" = "H" && "$Shift" = 3 ]]
then
echo "shift $Shift gets $$Bonus bonus"
else
echo "only hourly workers in"
echo "shift 3 get a bonus"
fi
*
EXAMPLE: USING THE || OPERATOR
#!/bin/bash
read -p "Enter calls handled:" CHandle
read -p "Enter calls closed: " CClose
if [[ "$CHandle" -gt 150 || "$CClose" -gt 50 ]]
then
echo "You are entitled to a bonus"
else
echo "You get a bonus if the calls"
echo "handled exceeds 150 or"
122. echo "calls closed exceeds 50"
fi
*
FILE TESTING
Meaning
-d file True if ‘file’ is a directory
-f file True if ‘file’ is an ord. file
-r file True if ‘file’ is readable
-w file True if ‘file’ is writable
-x file True if ‘file’ is executable
-s file True if length of ‘file’ is nonzero
*
EXAMPLE: FILE TESTING
#!/bin/bash
echo "Enter a filename: "
read filename
if [ ! –r "$filename" ]
then
echo "File is not read-able"
exit 1
fi
*
EXAMPLE: FILE TESTING
#! /bin/bash
if [ $# -lt 1 ]; then
echo "Usage: filetest filename"
123. exit 1
fi
if [[ ! -f "$1" || ! -r "$1" || ! -w "$1" ]]
then
echo "File $1 is not accessible"
exit 1
fi
*
EXAMPLE: IF… STATEMENT
# The following THREE if-conditions produce the same result
* DOUBLE SQUARE BRACKETS
read -p "Do you want to continue?" reply
if [[ $reply = "y" ]]; then
echo "You entered " $reply
fi
* SINGLE SQUARE BRACKETS
read -p "Do you want to continue?" reply
if [ $reply = "y" ]; then
echo "You entered " $reply
fi
* "TEST" COMMAND
read -p "Do you want to continue?" reply
if test $reply = "y"; then
echo "You entered " $reply
fi
*
EXAMPLE: IF..ELIF... STATEMENT
124. #!/bin/bash
read -p "Enter Income Amount: " Income
read -p "Enter Expenses Amount: " Expense
let Net=$Income-$Expense
if [ "$Net" -eq "0" ]; then
echo "Income and Expenses are equal - breakeven."
elif [ "$Net" -gt "0" ]; then
echo "Profit of: " $Net
else
echo "Loss of: " $Net
fi
*
THE CASE STATEMENTuse the case statement for a decision
that is based on multiple choices
Syntax:
case word in
pattern1) command-list1
;;
pattern2) command-list2
;;
patternN) command-listN
;;
esac
*
CASE PATTERNchecked against word for matchmay also
contain:
*
125. ?
[ … ]
[:class:]multiple patterns can be listed via:
|
*
[:digit:]
Digits: 0 1 2 3 4 5 6 7 8 9
[:alnum:]
Alphanumeric
[:alpha:]
[:lower:]
EXAMPLE 1: THE CASE STATEMENT
#!/bin/bash
echo "Enter Y to see all files including hidden files"
echo "Enter N to see all non-hidden files"
echo "Enter q to quit"
read -p "Enter your choice: " reply
case $reply in
Y|YES) echo "Displaying all (really…) files"
ls -a ;;
N|NO) echo "Display all non-hidden files..."
ls ;;
Q) exit 0 ;;
*) echo "Invalid choice!"; exit 1 ;;
esac
*
126. EXAMPLE 2: THE CASE STATEMENT
#!/bin/bash
ChildRate=3
AdultRate=10
SeniorRate=7
read -p "Enter your age: " age
case $age in
[1-9]|[1][0-2]) # child, if age 12 and younger
echo "your rate is" '$'"$ChildRate.00" ;;
# adult, if age is between 13 and 59 inclusive
[1][3-9]|[2-5][0-9])
echo "your rate is" '$'"$AdultRate.00" ;;
[6-9][0-9]) # senior, if age is 60+
echo "your rate is" '$'"$SeniorRate.00" ;;
esac
*
BASH PROGRAMMING: SO FARData
structureVariablesNumeric variablesArraysUser inputControl
structuresif-then-elsecase
*
BASH PROGRAMMING: STILL TO COME
Control structuresRepetitiondo-while, repeat-
untilforselectFunctionsTrapping signals
*
The Bash Shell
The Bash Shell
Copyright Department of Computer Science, Northern Illinois
127. University, 2005
09-*
Copyright Department of Computer Science, Northern Illinois
University, 2005
THE WHILE LOOPPurpose:
To execute commands in “command-list” as long as
“expression” evaluates to true
Syntax:
while [ expression ]
do
command-list
done
*
EXAMPLE: USING THE WHILE LOOP
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]
do
echo The counter is $COUNTER
let COUNTER=$COUNTER+1
done
*
EXAMPLE: USING THE WHILE LOOP
#!/bin/bash
128. Cont="Y"
while [ $Cont = "Y" ]; do
ps -A
read -p "want to continue? (Y/N)" reply
Cont=`echo $reply | tr [:lower:] [:upper:]`
done
echo "done"
*
Translate from lower case to upper case
THE UNTIL LOOPPurpose:
To execute commands in “command-list” as long as
“expression” evaluates to false
Syntax:
until [ expression ]
do
command-list
done
*
EXAMPLE: USING THE UNTIL LOOP
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]
do
echo $COUNTER
let COUNTER-=1
done
*
129. EXAMPLE: USING THE UNTIL LOOP
#!/bin/bash
Stop="N"
until [ $Stop = "Y" ]; do
ps -A
read -p "want to stop? (Y/N)" reply
Stop=`echo $reply | tr [:lower:] [:upper:]`
done
echo "done"
*
THE FOR LOOPPurpose:
To execute commands as many times as the number of
words in the “argument-list”
Syntax:
for variable in argument-list
do
commands
done
*
EXAMPLE 1: THE FOR LOOP
#!/bin/bash
for i in 7 9 2 3 4 5
do
echo $i
130. done
*
EXAMPLE 2: USING THE FOR LOOP
#!/bin/bash
# compute the average weekly temperature
for num in 1 2 3 4 5 6 7
do
read -p "Enter temp for day $num: " Temp
let TempTotal=$TempTotal+$Temp
done
let AvgTemp=$TempTotal/7
echo "Average temperature: " $AvgTemp
*
LOOPING OVER ARGUMENTSsimplest form will iterate over
all command line arguments:
#! /bin/bash
for parm
do
echo $parm
done
*
SELECT COMMANDConstructs simple menu from word
listAllows user to enter a number instead of a wordUser enters
sequence number corresponding to the word
131. Syntax:
select WORD in LIST
do
RESPECTIVE-COMMANDS
done
Loops until end of input, i.e. ^d (or ^c)
*
SELECT EXAMPLE
#! /bin/bash
select var in alpha beta gamma
do
echo $var
done
Prints:
*
1) alpha
2) beta
3) gamma
#? 2
beta
#? 4
#? 1
alpha
SELECT DETAILPS3 is select sub-prompt$REPLY is user input
(the number)
#! /bin/bash
PS3="select entry or ^D: "
select var in alpha beta
132. do
echo "$REPLY = $var"
done
*
Output:
select entry or ^D:
1) alpha
2) beta
? 2
2 = beta
? 1
1 = alpha
SELECT EXAMPLE
#!/bin/bash
echo "script to make files private"
echo "Select file to protect:"
select FILENAME in *
do
echo "You picked $FILENAME ($REPLY)"
chmod go-rwx "$FILENAME"
echo "it is now private"
done
*
BREAK AND CONTINUEInterrupt for, while or until loopThe
break statement transfer control to the statement AFTER the
done statementterminate execution of the loopThe continue
statementtransfer control to the statement TO the done
statementskip the test statements for the current
iterationcontinues execution of the loop
133. *
The Bash Shell
*
Copyright Department of Computer Science, Northern Illinois
University, 2005
THE BREAK COMMAND
while [ condition ]
do
cmd-1
break
cmd-n
done
echo "done"
*
This iteration is over and there are no more iterations
The Bash Shell
The Bash Shell
Copyright Department of Computer Science, Northern Illinois
University, 2005
09-*
Copyright Department of Computer Science, Northern Illinois
University, 2005
134. THE CONTINUE COMMAND
while [ condition ]
do
cmd-1
continue
cmd-n
done
echo "done"
*
This iteration is over; do the next iteration
The Bash Shell
The Bash Shell
Copyright Department of Computer Science, Northern Illinois
University, 2005
09-*
Copyright Department of Computer Science, Northern Illinois
University, 2005
EXAMPLE:
for index in 1 2 3 4 5 6 7 8 9 10
do
if [ $index –le 3 ]; then
echo "continue"
continue
fi
echo $index
if [ $index –ge 8 ]; then
135. echo "break"
break
fi
done
*
The Bash Shell
*
Copyright Department of Computer Science, Northern Illinois
University, 2005
DONE !
BASH SHELL PROGRAMMINGSequenceDecision:if-then-
elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps
*
still to come
SHELL FUNCTIONSA shell function is similar to a shell
scriptstores a series of commands for execution latershell stores
functions in memoryshell executes a shell function in the same
shell that called itWhere to defineIn .profileIn your scriptOr on
the command lineRemove a functionUse unset built-in
*
The Bash Shell
136. *
Copyright Department of Computer Science, Northern Illinois
University, 2005
SHELL FUNCTIONSmust be defined before they can be
referencedusually placed at the beginning of the script
Syntax:
function-name () {
statements
}
*
The Bash Shell
Copyright Department of Computer Science, Northern Illinois
University, 2005
EXAMPLE: FUNCTION
#!/bin/bash
funky () {
# This is a simple function
echo "This is a funky function."
echo "Now exiting funky function."
}
# declaration must precede call:
137. funky
*
The Bash Shell
Copyright Department of Computer Science, Northern Illinois
University, 2005
EXAMPLE: FUNCTION
#!/bin/bash
fun () { # A somewhat more complex function.
JUST_A_SECOND=1
let i=0
REPEATS=30
echo "And now the fun really begins."
while [ $i -lt $REPEATS ]
do
echo "-------FUNCTIONS are fun-------->"
sleep $JUST_A_SECOND
let i+=1
done
}
fun
*
FUNCTION PARAMETERSNeed not be declaredArguments
provided via function call are accessible inside function as $1,
$2, $3, …
$# reflects number of parameters
138. $0 still contains name of script
(not name of function)
*
EXAMPLE: FUNCTION WITH PARAMETER
#! /bin/sh
testfile() {
if [ $# -gt 0 ]; then
if [[ -f $1 && -r $1 ]]; then
echo $1 is a readable file
else
echo $1 is not a readable file
fi
fi
}
testfile *
*
EXAMPLE: FUNCTION WITH PARAMETERS
#! /bin/bash
checkfile() {
for file
do
if [ -f "$file" ]; then
echo "$file is a file"
else
if [ -d "$file" ]; then
echo "$file is a directory"
fi
fi
done
139. }
Checkfile $1 $2 $3
*
LOCAL VARIABLES IN FUNCTIONSVariables defined within
functions are global,
i.e. their values are known throughout the entire shell
program
keyword “local” inside a function definition makes referenced
variables “local” to that function
*
EXAMPLE: FUNCTION
#! /bin/bash
global="pretty good variable"
foo () {
xyz=124
echo “xyz inside function = $xyz”
local rrr="not so good variable"
echo $global
echo $rrr
global="better variable"
}
echo “xyz outside function = $xyz”
echo $global
foo
echo $global
echo $rrr
*
140. RECURSION;
FUNCTIONS CAN BE RECURSIVE - HERE'S A SIMPLE
EXAMPLE OF A FACTORIAL FUNCTION:
*
HANDLING SIGNALSUnix allows you to send a signal to any
process
-1 = hangup kill -HUP 1234 -2 = interrupt with ^C
kill -2 1235no argument = terminate kill 1235-9
= kill kill -9 1236-9 cannot be blocked
list your processes with
ps -u userid
*
LIST OF THE COMMONLY USED SIGNAL NUMBERS,
DESCRIPTION AND WHETHER THEY CAN BE TRAPPED
OR NOT:
*
SIGNALS ON LINUX
% kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16)
142. *
EXAMPLE: TRAP HANGUP
#! /bin/bash
trap 'echo dont terminate me’ 2
while true
do
echo "try to terminate"
sleep 1
done
*
EXAMPLE: TRAP MULTIPLE SIGNALS
#! /bin/sh
trap 'echo 2’ 2
trap 'echo 3’ 3
while true; do
echo -n .
sleep 1
done
*
EXAMPLE: REMOVING TEMP FILES
#! /bin/bash
cleanup () {
/bin/rm -f /tmp/tempfile.$$.?
143. }
trap 'cleanup; exit' 2
for i in 1 2 3 4 5 6 7 8
do
echo "$i.iteration"
touch /tmp/tempfile.$$.$i
sleep 1
done
cleanup
*
RESTORING DEFAULT HANDLERStrap without a command
list will remove a signal handlerUse this to run a signal handler
once only
#! /bin/sh
trap 'justonce' 2
justonce() {
echo "not yet"
trap 2 # now reset it
}
while true; do
echo -n "."
sleep 1
done
*
144. DONE !
SUMMARY: BASH SHELL
PROGRAMMINGSequenceDecision:if-then-
elsecaseRepetitiondo-while, repeat-untilforselectFunctionsTraps
*
The vi Editor
The vi EditorWhen you write some C or Java programs or shell
(or perl) scripts, or edit some system files, you need to use an
editor.There are two versatile editors in UNIX – vi and emacs.vi
is a full-screen editor. It was created by a graduate student –
Bill Joy – later to become the cofounder of Sun Microsystems.
The vi/vim EditorA vi session begins by invoking the command
vi with (or without) a filename:
vi myfileYou are presented a full empty screen, each line
beginning with a ~ (tilde).
The vi/vim EditorThe ~ is vi’s way to indicating that they are
nonexistent line.For text editing, vi uses 24 of the 25 lines that
are normally available in a terminal. The last line is reserved
for some commands that you’ll enter to act on the text. This line
is also used by the system to display messages.
145. The Three ModesThere are three modes in which vi
works:Command Mode – Where keys are used as commands to
act on text.Input Mode – Where any key depressed is entered as
text.Last Line Mode - Where commands can be entered in the
last line of the screen to act on text.
Quitting vi – The Last Line ModeThe editor works with a copy
of the file which is placed in a buffer that is simply a temporary
storage area which is associated with the file on disk.It is
necessary to know how to leave the editor. Saving and quitting
are handled by the Last Line Mode.Every command in this mode
is preceded by a : (colon) and followed by the [Enter] key.
Quitting vi – The Last Line ModeRemember to leave the Input
Mode by pressing the [Esc] key.The Last Line Mode offers two
ways of saving and quitting - :x and :wq.The commands return
you to the shell after saving your work.
Quitting vi – The Last Line ModeTo abort editing, you can use
q (quit) command.The q command takes you out of the editor
only if you don’t have a changed buffer.
: q [Enter]
$The q! command always return you to the prompt irrespective
of the status of the buffer.
146. Quitting viThese are exit commands in vi::x – saves files and
quits editing mode:wq – saves files and quits editing mode.:q –
quits editing mode when no changes are made to file:q! – quits
editing mode but after abandoning changes.:sh – escapes to
UNIX shell (use exit to return to vi).
Inserting and Replacing TextBefore you are able to enter text,
you have to change from the default Command Mode to Input
Mode.You can set the editor in showmode (with :set showmode)
to display a suitable message in the last line.The simplest type
of input is insertion of text.
Inserting and Replacing TextWhen vi is invoked, the cursor is
always positioned at the first character of the first line.To insert
text at this position, press i. The character doesn’t show up on
the screen, but pressing this key changes the mode from
Command to Input.Since the showmode setting was made,
you’ll see the words INSERT or INSERT MODE in the last line.
Inserting and Replacing TextFurther key depressions will show
text on the screen as it is being entered.
This is the vi editor
It is quite powerful.
It operates in three modes.
Inserting and Replacing TextYou can use [Backspace] to correct
a mistake or erase the previous word using [Ctrl-w].After you