Unii 2 Linux Programming New
Unii 2 Linux Programming New
Linux Programming
II-UNIT
What iss shel
shell ?
shell recognizes the special character * and substitutes on the command line
the names of all files in the current directory
/O Redi
I/O Redirection
ection
It scans the command line for the occurrence of
the special redirection characters <, >, or >>
P peline Hookup
Pipeline
Shell connects the standard output from the command
preceding the | to the standard input of the one following the |. It
then initiates execution of both programs.
Syntax: command_1 | command_2 [| command_3 . . . ]
P peline Hookup
Pipeline
How to find the number of lines in a file?
Environment Control
Cont ol
An environment variable is a dynamic-named value
that can affect the way running processes will behave
on a computer. They are part of the environment in
which a process runs
• Give information about the system behavior
n erpreted Programming
Interpreted ProgrammingLanguage
Language
•The shell has its own built-in programming language.
•This language is interpreted, meaning that the shell
analyzes each statement in the language one line at
•
a time and then executes it.
This differs from programming languages such as C
equivalents.
•
variables, and functions, and is procedure-oriented.
Modern shells based on the IEEE POSIX standard
Pipes:
Standard output of one program used as
standard input to next program
Used with filter commands to further
refine data
Not limited to two programs
Pipe symbol is the vertical broken bar | and is
used between two commands.
snist@snist-HP-280-G2-SFF:~/mamata$ who > f1.txt
snist@snist-HP-280-G2-SFF:~/mamata$ cat f1.txt
snist tty7 2017-12-27 14:41 (:0
snist@snist-HP-280-G2-SFF:~/mamata$ who | wc -l
1
Here, the output of who has been passed directly to the
input of wc. And who is said to be piped to wc .
• You can know use one to count the number of files in the
current directory
• snist@snist-HP-280-G2-SFF:~/mamata$ ls | wc -l
3
snist@snist-HP-280-G2-SFF:~/mamata$
$ script_name
• Child Shell Execution
• To ensure the script is properly executed, we can create a
child shell and execute it in the new shell.
• This done by specifying the shell before the script name as
in the following example:
$ bash script_name
Creating a Script
To create a shell script first use a text editor to create
a file containing the commands.
For example, type the following commands and
save them as first.sh
#!/bin/sh
is special and tells the system to use the /bin/sh program
to execute this program.
The command exit 0
Causes the script program to exit and return a
value of 0, which means there were not errors.
Making a Script Executable
There are two ways to execute the script.
1) invoke the shell with the name of the script file as a
parameter, thus:
/bin/sh first.sh (Or )
2) change the mode of the script to executable and then after
execute it by just typing its name.
chmod +x first.sh first.sh
Actually, you may need to type:
./first.sh
to make the file execute unles the path variable has your
directory in it.
Shell Metacharacters
1. File name substitution.
2. I/O Redirection.
3. Process execution.
4. Quoting Metacharacters.
5. Positional parameters.
6. Special characters.
F e name substitution
File subs ution ( ?,
?, *,
*, [..],[!..]
.] .. )
$ls a?b? list of all files whose first character is ‘a’ and
third character is ‘b’
Example
$ ls > myfile 2 > &1
o/p : consists o/p of ls in file myfile.
$ a=5
$ echo “value of a is $a”
5
$ echo ‘value of a is $a’
value of a is $a
EXAMPLES
• # | Expression | Result | Comment
• 1 | "$a" | apple | variables are expanded inside ""
• 2 | '$a' | $a | variables are not expanded inside ''
• 3 | "'$a'" | 'apple' | '' has no special meaning inside "“
• 4 | '"$a"' | "$a" | "" is treated literally inside ''
• 5 | '\'' | **invalid** | can not escape a ' within ''; use "'" or $'\'' (ANSI-
C quoting)
• 6 | "red$arocks"| red | $arocks does not expand $a; use ${a}rocks to
preserve $a
• 7 | "redapple$" | redapple$ | $ followed by no variable name
evaluates to $
• 8 | '\"' | \" | \ has no special meaning inside '‘
• 9 | "\'" | ' | \' is interpreted inside ""
• 10 | "\"" | " | \" is interpreted inside ""
EXAMPLES
$ echo this is a *
$ echo this is a \*
$ echo ‘$,\,?, all just the way they look”
$ echo “ your name is $name”
• $# = 3
• $* = -yes -no /home/username
• $@ = array: {"-yes", "-no", "/home/username"}
Command Substitution
•When a Shell executes a command, the output is
directed to standard output( most of the time, standard
output is associated with monitor)
• Shell allows the standard output of one command to
be used as an argument of another command
• Some times we need to change the output to a string
that we can store in another string or a variable .
• Command substitutions provides the capability to
convert the result of a command to a string
Without command substitution
suma 60
•The command substitution operator that converts the
output of a command to a string is a dollar sign and a
set of parentheses.
• Backquote ( ` ` )or backtick is another metacharacter
that used for command substitution
•When scanning the command line, the shell executes
the enclosed command and replaces the enclosed
command line with the out put of the command
command
Without command substitution
$(command) string
suma 61
You can use this feature to generate meaningful messages
Ex:
$ echo “ There are ` ls | wc –l ` file in the current directory”
There are 58 files in the current directory
Example: $ i = 10 ; j = 10
$ echo `expr $i + $j`
20
$ echo `expr $i \* $j`
100 63
2) who | sort
• who command displays who logged onto the system and
provides an account of all users
• It displays a three column output, the first column displays
the user-ids of users currently working on the system.
• The second column displays the system name.
• The third column displays the date and time.
• Sort command sorts text files. It sorts all the lines from the
standard input.
• who | sort before displaying the who output on the screen it
is piped to sort.
• Sort receives the output of who as standard input, it then
sorts the output according to the first alphabet in each line
and displays it on screen
64
3) ls | wc –l
suma 66
4) break
• Break statement causes the control to come out of the loop instantly.
• It terminates the loop.
# break.sh
#!/bin/sh
x=5
while[$x –gt 3] #outer while loop
do y = 5
while[$y –gt 2] #inner while loop
do
if[$y –eq 3]
then
break; #immediately terminates inner loop when y =3
else
echo $x $y
fi
y = ‘expr $y – 1’
done suma 67
5) tee command
• The tee command copies standard input to standard output
and at the same time copies it to one or more files.
• If the stream is coming from another command, such as
who, it can be piped to the tee command.
Example:
$The following command (with the help of tee command)
writes the output both to the screen (stdout) and to the file.
$ ls | tee file
suma 68
By default tee command overwrites the file. You can
instruct tee command to append to the file using the
option –a as shown below.
$ ls | tee –a file
You can also write the output to multiple files as
shown below.
$ ls | tee file1 file2 file3
6) Aliases
• An alias provides a means of creating customized
commands by assigning a name to a command.
• An alias is created by using the alias command. Its format is
alias name=command-definition
Example :
Using alias to rename the list command
$ alias dir=ls
$ dir
alias of command with options
$alias dir=‘ls –l’
$ dir
Listing aliases Removing all
aliases
$alias $unalias -a
Removing aliases
suma 70
$alias dir
7) eval command
• The eval command is used when the Bourne shell needs to
evaluate a command twice before executing it.
Example 1:
If we need to store the name of a variable in a second
variable and then use the print command to display the
value of the original variable. Example-2:
Wrong way to use a variable in a variable
$x=23
$y=x
$print $y
x
Another wrong way to use a variable in a variable
$x=23
$y=x
$print \$$y
$x
Correct way to use a variable in a variable 71
Example-2: To execute that command stored in the string
/home/mamatha > a="ls | more“
/home/mamatha > $a
bash: command not found: ls | more
/home/user1 > # Above command didn't work as ls tried to list
file with name pipe (|) and more. But these files are not there
/home/mamatha > eval $a
file.txt
mailids
remote_cmd.sh
sample.txt
Tmp
/home/mamatha >
Example-3:To print the value of variable which is again variable with value assigned to
it
$ a=10
$ b=a
$ c='$'$b ( note: The dollar sign must be escaped with '$')
$ echo $c
output:
$a
$ eval c='$'$b
$ echo $c
output:
10
Quoting
• Shell uses a selected set of metacharcters in commands.
• Metacharcters are characters that have a special interpretation.
For example the pipe (|)
• In order to use them as a normal text we must tell the shell
interpreter that they should be interpreted differently. This is
called quoting the metacharcters.
• To achieve quoting there are three metacharcters collectively
as quotes,
Quotes
Double Single
Backslash
Quotes Quotes
74
Backslash
• The backslash metacharcter (\) is used to change the
interpretation of the character that follows it, i.e., it converts a
literal character into a special character and vice versa.
Example:
• The character n is interpreted as a literal character by the shell
to change its interpretation as a newline character we use
backslash before it (\n).
• Similarly the use of a greater than symbol (>) in a command is
interpreted as a special character (output redirection), to
change its interpretation as a literal text we use a backslash
before it (\>)
Example:
$ echo “Metacharcters are : >,<,?,|,&“
Metacharcters are : >,<,?,|,&
$ echo a = 10
$ echo “a is $a and single quote is ‘b’ “
76
a is 10 and single quote is ‘b’
Single Quotes
Example:
$ echo a = 10
$ echo ‘characters are < > “b” $a ? &’
characters are < > “b” $a ? &
77
Control Structures
• Control structures alter the flow of the program
1. if-then-else
2. case
3. loops
a. for
b. while
c. Until
4.Handling signals
78
• THE SIMPLE IF STATEMENT
SYNTAX:
if [ condition ]; then
statements
Fi
• Executes the statements only if condition is true
Ex:
#!/bin/bash
# Basic if statement
if [ $1 -gt 100 ]
then
echo Hey that\'s a large number.
pwd
fi 79
Output: ./ if_example.sh 15
Sat 6 Jan 5:06:35 2018
$ ./if_example.sh 150
· Hey that's a large number.
· /home/ryan/bin
· Sat 6 Jan 5:06:35 2018
• THE IF-THEN-ELSE STATEMENT
if [ condition ]; then
statements-1
else
statements-2
fi
81
• THE NESTED IF
if [ condition ]; then
statements
elif [ condition ]; then
statement
else
statements
fi
[ -u FILE ] True if FILE exists and its SUID (set user ID) bit is set.
[ -O FILE ] True if FILE exists and is owned by the effective user ID.
[ -G FILE ] True if FILE exists and is owned by the effective group ID.
Operation Effect
• Purpose:
To execute commands in “command-list” as long as
“expression” evaluates to true
Syntax:
while [ expression ]
do
command-list
done
suma 89
THE UNTIL LOOP
• Purpose:
To execute commands in “command-list” as long as
“expression” evaluates to false
Syntax:
until [ expression ]
do
command-list
done
suma 90
The while loop vs the until loop
The until loop executes until a nonzero status is
returned.
The while command executes until a zero status is
returned.
The until loop always executes at least once
Example
Create a shell script called f1.sh:
#!/bin/bash
i=1
until [ $i -gt 6 ]
do
echo "Welcome $i times."
i=$(( i+1 ))
done
save and close the file. Run it as follows:
$ chmod +x until.sh
$ ./until.sh
outputs:
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.
Welcome 5 times.
Welcome 6 times.
THE FOR LOOP
• Purpose:
To execute commands as many times as the number of
words in the “argument-list”
Syntax:
for variable in argument-list
do
commands
done
suma 93
Example :
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
Do
echo $var
Done
• -9 cannot be blocked
2 SIGINT Interrupt
3 SIGQUIT Quit
6 SIGABRT Abort
15 SIGTERM Terminate
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) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
^C is 2 - SIGINT
suma 97
Handling signals
•When you press the Ctrl+C or Break key at your terminal during
execution of a shell program, normally that program is
immediately terminated, and your command prompt returns. This
may not always be desirable. For instance, you may end up
leaving a bunch of temporary files that won't get cleaned up.
Syntax:
trap 'handler commands' signals
suma 98
Example:
trap 'echo do not hangup' 1 2
Syntax:
expr op1 math-operator op2
Examples:
$ expr 1 + 3
$ expr 2 - 1
$ expr 10 / 2
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 6 + 3`
Note:
expr 20 %3 - Remainder
suma read as 20 mod 3 and remainder
100 is 2.
expr 10 \* 3 - Multiplication use \* and not * since its wild card.
Shell Arithmetic
(1) First, before expr keyword we used ` (back quote) sign not the (single
quote i.e. ') sign. Back quote is generally found on the key under tilde (~)
on PC keyboard OR to the above of TAB key.
(4) Here if you use double quote or single quote, it will NOT work
For e.g.
$ echo "expr 6 + 3" # It will print expr 6 + 3
$ echo 'expr 6 + 3' # It will print expr 6 + 3
suma 101
TEST COMMAND
Checks file types and compares values.
test is used as part of the conditional execution of shell
commands.
test exits with the status determined by EXPRESSION.
Placing the EXPRESSION between square brackets
([ and ]) is the same as testing the EXPRESSION with test.
To see the exit status at the command prompt, echo the
value "$?" A value of 0 means the expression evaluated as
true, and a value of 1 means the expression evaluated as
false.
Syntax:
test EXPRESSION
(or)
[ EXPRESSION ]
Examples:
test 100 -gt 99 && echo "Yes, that's true." || echo "No, that's
false."
This command will print the text "Yes, that's true." because
100 is greater than 99.
test 100 -lt 99 && echo "Yes." || echo "No.“
This command will print the text "No." because 100 is not less
than 99.
[ "awesome" = "awesome" ];
echo $?
This command will print "0" because the expression is true;
the two strings are identical.
[ 5 -eq 6 ];
echo $?
This command will print "1" because the expression is false;
5 does not equal 6.
Comparing Numbers:
If you are comparing elements that parse as numbers you can
use the following comparison operators:
-eq - does value 1 equal value 2
-ge - is value 1 greater or equal to value 2
-gt - is value 1 greater than value 2
-le - is value 1 less than or equal to value 2
-lt - is value 1 less than value 2
-ne - does value 1 not equal value 2
Comparing Text:
If you are comparing elements that parse as strings you can
use the following comparison operators:
= - does string 1 match string 2
!= - is string 1 different to string 2
-n - is the string length greater than 0
-z - is the string length 0
Examples:
test "string1" = "string2" && echo "yes" || echo "no"
(displays "no" to the screen because "string1" does not
equal "string2")
Functions
A shell function is similar to a shell script
stores a series of commands for execution later
shell stores functions in memory
shell executes a shell function in the same shell that
called it
Where to define
In .profile
In your script
Or on the command line
Remove a function
Use unset built-in
suma 107
• must be defined before they can be referenced
• usually placed at the beginning of the script
Syntax:
function-name () {
statements
}
suma 108
Function parameters
suma 109
Local Variables in Functions
• Variables defined within functions are global, i.e. their
suma 110
#!/bin/sh
# Define your function here
Hello ()
{ echo "Hello World $1 $2“
return 10 }
# Invoke your function
Hello Zara Ali
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
Output:
$./test.sh
Hello World Zara Ali
Return value is 10
#!/bin/sh
myfunc()
{
echo "I was called as : $@“
x=2 }
### Main script starts here
echo "Script was called with $@"
x=1
echo "x is $x" Output:
myfunc 1 2 3 $ scope.sh a b c
echo "x is $x” Script was called with a b c
x is 1
I was called as : 1 2 3
x is 2
Debugging Shell Scripts
• Debugging is troubleshooting errors that may occur
during the execution of a program/script
• The following two commands can help you debug a
bash shell script:
• echo
use explicit output statements to trace execution
• set
suma 113
Debugging using “set”
• The “set” command is a shell built-in command
• has options to allow flow of execution
–v option prints each line as it is read
–x option displays the command and its arguments
–n checks for syntax errors
• options can turned on or off
To turn on the option: set -xv
To turn off the options: set +xv
(or)
The -x option, short for xtrace or execution trace, tells the
shell to echo each command after performing the substitution
steps Thus , we can see the values of variables and commands.
Often, this option alone will help to diagnose a problem.
Ex:
•We can use set –x command in shell script itself:
#!/bin/bash
clear
# turn on debug mode
set –x
for f in *
do
file $f
done
# turn OFF debug mode
set +x
ls # more commands
The -v option tells the shell to run in verbose mode. In
practice , this means that shell will echo each command prior
to execute the command. This is very useful in that it can
often help to find the errors.
Ex:
snist:~/mamta> set –v
snist:~/mamta> ls
ls
commented-scripts.sh script1.sh
snist:~/mamta> set +v
set +v
snist:~/mamta> ls *
commented-scripts.sh script1.sh
The -n option, shot for noexec ( as in no execution), tells the shell to
not run the commands. Instead, the shell just checks for syntax errors.
This option will not convince the shell to perform any more checks.
Instead the shell just performs the normal syntax check. With -n option,
the shell doesn’t execute your commands, so you have a safe way to test
your scripts if they contain syntax erro
Ex: shell script name debug_quotes.sh
#!/bin/bash
echo "USER=$USER
echo "HOME=$HOME"
echo "OSNAME=$OSNAME"
Now run the script with -n option
$ sh -n debug_quotes
debug_quotes: 8: debug_quotes: Syntax error: Unterminated
quoted string.
We can use the debug function for debugging specific statement in the
shell script. An example is shown below:
#!/bin/bash
_DEBUG="on“
function DEBUG()
{ [ "$_DEBUG" == "on" ] && $@
}
DEBUG echo 'Printing Numbers'
for i in `seq 1 3`
do
echo $i done