No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore 560076. Website: WWW - Proximo.in
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore 560076. Website: WWW - Proximo.in
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore 560076. Website: WWW - Proximo.in
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Linux Tutorial
Linux 1
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Introduction
This tutorial is designed for beginners only and This tutorial explains the basics of shell
programming by showing some examples of shell programs. Its not help or manual for the
shell. While reading this tutorial you can find manual quite useful ( type man bash at $
prompt to see manual pages). Manual contains all necessary information you need, but it
won't have that much examples, which makes idea more clear. For that reason, this tutorial
contains examples rather than all the features of shell. I assumes you have at least working
knowledge of Linux i.e. basic commands like how to create, copy, remove files/directories
etc or how to use editor like vi or mcedit and login to your system. Before Starting Linux
Shell Script Programming you must know
● Kernel
● Shell
● Process
● Redirectors, Pipes, Filters etc.
What's Kernel
Kernel is hart of Linux O/S. It manages resource of Linux O/S. Resources means facilities
available in Linux. For eg. Facility to store data, print data on printer, memory, file
management etc . Kernel decides who will use this resource, for how long and when. It
runs your programs (or set up to execute binary files) It's Memory resident portion of
Linux. It performance following task :
● I/O management
● Process management
● Device management
● File management
● Memory management
This is what Shell Does for US It's environment provided for user interaction. Shell is an
command language interpreter that executes commands read from the standard input
device (keyboard) or from a file. Linux may use one of the following most popular shells (In
MS-DOS, Shell name is COMMAND.COM which is also used for same purpose, but it's not as
powerful as our Linux Shells are!)
Linux 2
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Any of the above shell reads command from user (via Keyboard or Mouse) and tells Linux
O/s what users want. If we are giving commands from keyboard it is called command line
interface ( Usually in-front of $ prompt, This prompt is depend upon your shell and
Environment that you set or by your System Administrator, therefore you may get different
prompt ). NOTE: To find your shell type following command
$ echo $SHELL
NOTE that following commands are for New users or for Beginners only. The purpose is if
you use this command you will be more familiar with your shell and secondly, you need
some of these command in your Shell script. If you want to get more information or help for
Linux 3
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
this command try following commands For e.g. To see help or options related with date
command try
$ date --help
or To see help or options related with ls command (Here you will screen by screen help,
since help of ls command is quite big that can't fit on single screen ) See what happened
when you type following
Syntax: command-name --help
Syntax: man command-name
Syntax: info command-name
Linux Command
Linux 4
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Linux 5
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Linux 6
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
What is Processes Process is any kind of program or task carried out by your PC. For e.g.
$ ls -lR , is command or a request to list files in a directory and all subdirectory in your
current directory. It is a process. A process is program (command given by user) to perform
some Job. In Linux when you start process, it gives a number (called PID or process-id),
PID starts from 0 to 65535.
Linux 7
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
NOTE that you can only kill process which are created by yourself. A Administrator can
almost kill 95-98% process. But some process can not be killed, such as VDU Process.
Linux 8
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Pips
A pipe is a way to connect the output of one program to the input of another
program without any temporary file.
A pipe is nothing but a temporary storage place where the output of one command is stored
and then passed as the input for second command. Pipes are used to run more than two
commands ( Multiple commands) from same command line. Syntax: command1 |
command2
Linux 9
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Filter
If a Linux command accepts its input from the standard input and produces its output on
standard output is know as a filter. A filter performs some kind of process on the input and
gives output. For e.g.. Suppose we have file called 'hotel.txt' with 100 lines data, And from
'hotel.txt' we would like to print contains from line number 20 to line number 30 and store
this result to file called 'hlist' then give command
$ tail +20 < hotel.txt | head -n30 >hlist
Here head is filter which takes its input from tail command (tail command start
selecting from line number 20 of given file i.e. hotel.txt) and passes this lines to input
to head, whose output is redirected to 'hlist' file.
Variables in Linux
Sometimes to process our data/information, it must be kept in computers RAM memory.
RAM memory is divided into small locations, and each location had unique number called
memory location/address, which is used to hold our data. Programmer can give a unique
name to this memory location/address called memory variable or variable (Its a named
storage location that may take different values, but only one at a time). In Linux, there are
two types of variable 1) System variables - Created and maintained by Linux itself. This
type of variable defined in CAPITAL LETTERS. 2) User defined variables (UDV) - Created
and maintained by user. This type of variable defined in lower LETTERS.
Some System variables You can see system variables by giving command like $ set,
Some of the important System variables are
Linux 10
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
NOTE that Some of the above settings can be different in your PC. You can print any of the
above variables contain as follows
$ echo $USERNAME $ echo $HOME
Caution: Do not modify System variable this can some time create problems.
Rules for Naming variable name (Both UDV and System Variable)
.(1) Variable name must begin with Alphanumeric character or underscore character (_),
followed byone or more Alphanumeric character. For e.g. Valid shell variable are as follows
HOME SYSTEM_VERSION vech no
.(2) Don't put spaces on either side of the equal sign when assigning value to variable.
For e.g.. Infollowing variable declaration there will be no error
$ no=10
But here there will be problem for following
$ no =10 $ no= 10 $ no = 10
Linux 11
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
.(3) Variables are case-sensitive, just like filename in Linux. For e.g.
.$ no=10 $ No=11 $ NO=20 $ nO=2 Above all are different variable name, so to print
value 20 we have to use $ echo $NO and Not any
.(4) You can define NULL variable as follows (NULL variable is variable which has no value
at the timeof definition) For e.g.
.$ vech=
$ vech=""
Try to print it's value $ echo $vech , Here nothing will be shown because variable has no
value i.e.
NULL variable.
of the following
$ echo $no # will print 10 but not 20
$ echo $No # will print 11 but not 20
$ echo $nO # will print 2 but not 20
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
Linux 12
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
$ cat > first # # My first shell script # clear echo "Knowledge is Power"
Press Ctrl + D to save. Now our script is ready. To execute it type command
$ ./first
This will give error since we have not set Execute permission for our script first; to do
this type command
$ chmod +x first $ ./first
First screen will be clear, then Knowledge is Power is printed on screen. To print
message of variables contains we user echo command, general form of echo
command is as follows
echo "Message"
echo "Message variable1, variable2....variableN"
Linux 13
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
created one script called 'first', after creation of this script you moved to some other
directory lets say /home/vivek/Letters/Personal, Now if you try to execute your script it will
not run, since script 'first' is in /home/vivek directory, to Overcome this problem there are
two ways First, specify complete path of your script when ever you want to run it from other
directories like giving following command
$ /bin/sh /home/vivek/first
Now every time you have to give all this detailed as you work in other directory, this take
time and you have to remember complete path. There is another way, if you notice that all
of our programs (in form of executable files) are marked as executable and can be directly
executed from prompt from any directory (To see executables of our normal program give
command $ ls -l /bin or ls -l /usr/bin) by typing command like
$ bc $ cc myprg.c $ cal
etc, How this happed? All our executables files are installed in directory called /bin and /bin
directory is set in your PATH setting, Now when you type name of any command at $
prompt, what shell do is it first look that command in its internal part (called as internal
command, which is part of Shell itself, and always available to execute, since they do not
need extra executable file), if found as internal command shell will execute it, If not found It
will look for current directory, if found shell will execute command from current directory, if
not found, then Shell will Look PATH setting, and try to find our requested commands
executable file in all of the directories mentioned in PATH settings, if found it will execute it,
otherwise it will give message "bash: xxxx :command not found", Still there is one question
remain can I run my shell script same as these executables. Yes you can, for this purpose
create bin directory in your home directory and then copy your tested version of shell script
to this bin directory. After this you can run you script as executable file without using $
./shell script-name syntax, Following are steps
$ cd $ mkdir bin $ cp first ~/bin $ first
Each of above command Explanation
Linux 14
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
In shell script comment is given with # character. This comments are ignored by your shell.
Comments are used to indicate use of script or person who creates/maintained script, or for
some programming explanation etc. Remember always set Execute permission for you
script.
(2)More about Quotes There are three types of quotes " i.e. Double Quotes ' i.e. Single
quotes ` i.e. Back quote 1."Double Quotes" - Anything enclose in double quotes removed
meaning of that characters (except \ and $).
1. 2. 'Single quotes' - Enclosed in single quotes remains unchanged.
2. 3. `Back quote` - To execute command.For eg.
Linux 15
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
NOTE: $# holds number of arguments specified on command line. and $* or $@ refer to all
arguments in passed to script. Now to obtain total no. of Argument to particular script, your
$# variable.
Linux 16
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Second command line argument passed to myshell i.e. bar In shell if we wish to refer this
command line argument we refer above as follows
myshell it is $0
foo it is $1
bar it is $2 Here $# will be 2 (Since foo and bar only two Arguments), Please note At a
time such 9 arguments can be used from $0..$9, You can also refer all of them by using $*
Linux 17
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
(which expand to `$0,$1,$2...$9`) Now try to write following for commands, Shell Script
Name ($0), No. of Arguments (i.e. $#), And actual argument (i.e. $1,$2 etc)
For e.g. now will write script to print command ling argument and we will see how to access
them
$ cat > demo #!/bin/sh # # Script that demos, command line args # echo "Total
number of command line argument are $#" echo "$0 is script name" echo "$1 is
first argument" echo $2 is second argument" echo "All of them are :- $*"
(5)Exit Status By default in Linux if particular command is executed, it return two type of
values, (Values are used to see whether command is successful or not) if return value is
zero (0), command is successful, if return value is nonzero (>0), command is not successful
or some sort of error executing command/shell script. This value is know as Exit Status of
that command. To determine this exit Status we use $? variable of shell. For eg.
$ rm unknow1file
It will show error as follows rm: cannot remove `unkowm1file': No such file or directory and
after that if you give command $ echo $? it will print nonzero value(>0) to indicate error.
Now give command
$ ls $ echo $?
It will print 0 to indicate command is successful. Try the following commands and not
down there exit status
$ expr 1 + 3 $ echo $?
Linux 18
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
$ date $ echo $?
$ echon $?
$ echo $?
(6)if-then-fi for decision making is shell script Before making any decision in Shell script you
must know following things Type bc at $ prompt to start Linux calculator program $ bc
After this command bc is started and waiting for you commands, i.e. give it some
calculation as follows type 5 + 2 as
5+27
7 is response of bc i.e. addition of 5 + 2 you can even try
5-25/2
Now what happened if you type 5 > 2 as follows
5>20
0 (Zero) is response of bc, How? Here it compare 5 with 2 as, Is 5 is greater then 2, (If I
ask same question to you, your answer will be YES) In Linux (bc) gives this 'YES' answer by
showing 0 (Zero) value. It means when ever there is any type of comparison in Linux Shell
It gives only two answer one is YES and NO is other.
Try following in bc to clear your Idea and not down bc's response
5 > 12 5 == 10 5 != 2 5 == 5 12 < 2
Linux 19
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Now will see, if condition which is used for decision making in shell script, If given condition
is true
then command1 is executed.
Syntax:
if condition
then
command1 if condition is true or if exit status
of condition is 0 (zero)
...
...
fi Here condition is nothing but comparison between two values, for compression we
can use test or [ expr ] statements or even exist status can be also used. An expression is
nothing but combination of values, relational operator (such as >,<, <> etc) and
mathematical operators (such as +, -, / etc ). Following are all examples of expression: 5 >
2 3 + 6 3 * 65 a < b c > 5 c > 5 + 30 -1 Type following command (assumes you have file
called foo)
$ cat foo $ echo $?
The cat command return zero(0) on successful, this can be used in if condition as follows,
Write shell script as
$ cat > showfile #!/bin/sh # #Script to print file # if cat $1 then
echo -e "\n\nFile $1, found and
successfully echoed" fi
Linux 20
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Run it as follows
$ chmod +x ispostive $ ispostive 5
Here o/p : 5 number is positive
$ispostive -45
Here o/p : Nothing is printed
$ispostive
Here o/p : ./ispostive: test: -gt: unary operator expected The line, if test $1 -gt 0 , test to
see if first command line argument($1) is greater than 0. If it is true(0) then test will return
0 and output will printed as 5 number is positive but for -45 argument there is no output
because our condition is not true(0) (no -45 is not greater than 0) hence echo statement is
skipped. And for last statement we have not supplied any argument hence error ./ispostive:
test: -gt: unary operator expected is generated by shell , to avoid such error we can test
whether command line argument is supplied or not. (See command 8 Script example). test
or [ expr ] works with 1.Integer ( Number without decimal point) 2.File types 3.Character
strings For Mathematics use following operator in Shell Script
Linux 21
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Logical Operators Logical operators are used to combine two or more condition at a time
Linux 22
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
(8)if...else...fi
If given condition is true then command1 is executed otherwise command2 is executed.
Syntax:
if condition
then
command1 if condition is true or if exit status
of condition is 0(zero)
...
...
else
command2 if condition is false or if exit status
of condition is >0 (nonzero)
...
...
fi
if test $1 -gt 0 then echo "$1 number is positive" else echo "$1
number is negative" fi
Try it as follows
$ chmod +x isnump_n $ isnump_n 5
Here o/p : 5 number is positive
$ isnump_n -45
Here o/p : -45 number is negative
$ isnump_n
Here o/p : ./ispos_n : You must give/supply one integers
$ isnump_n 0
Here o/p : 0 number is negative Here first we see if no command line argument is given
then it print error message as "./ispos_n : You must give/supply one integers". if statement
checks whether number of argument ($#) passed to script is not equal (-eq) to 0, if we
Linux 23
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
passed any argument to script then this if statement is false and if no command line
argument is given then this if statement is true. The echo command i.e. echo "$0 : You
must give/supply one integers"
||
||
12
1 will print Name of script 2 will print this error message And finally statement exit 1 causes
normal program termination with exit status 1 (nonzero means script is not successfully
run), The last sample run $ isnump_n 0 , gives output as "0 number is negative", because
given argument is not > 0, hence condition is false and it's taken as negative number. To
avoid this replace second if statement with if test $1 -ge 0.
if condition
then
condition is zero (true - 0)
execute all commands up to elif
statement
elif condition1
condition1 is zero (true - 0)
execute all commands up to elif
statement
elif condition2
condition2 is zero (true - 0)
execute all commands up to elif
statement
else
None of the above condtion,condtion1,condtion2 are true (i.e.
all of the above nonzero or false)
execute all commands up to fi
fi
For e.g. Write script as $ cat > elf #!/bin/sh # # Script to test if..elif...else # # if [
$1 -gt 0 ]
then echo "$1 is positive" elif [ $1 -lt 0 ] then echo "$1 is negative" elif [ $1 -eq 0
Linux 24
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
]
then echo "$1 is zero" else echo "Opps! $1 is not number, give number" fi Try
above
script with $ chmod +x elf $ ./elf 1 $ ./elf -2 $ ./elf 0 $ ./elf a Here o/p for last
sample run: ./elf: [: -gt: unary operator expected ./elf: [: -lt: unary operator expected
./elf: [: -eq:
unary operator expected Opps! a is not number, give number Above program gives error for
last
run, here integer comparison is expected therefore error like "./elf: [: -gt: unary operator
expected"
occurs, but still our program notify this thing to user by providing message "Opps! a is not
number,
give number". (10)Loops in Shell Scripts
Computer can repeat particular instruction again and again, until particular condition
satisfies. A
group of instruction that is executed repeatedly is called a loop.
do
execute one for each item in the list until the list is
not finished (And repeat all statement between do and
done)
done
Suppose,
$ cat > testfor for i in 1 2 3 4 5 do
echo "Welcome $i times" done
Run it as,
$ chmod +x testfor $ ./testfor
The for loop first creates i variable and assigned a number to i from the list of number
from 1 to 5, The shell execute echo statement for each assignment of i. (This is usually
know as iteration) This process will continue until all the items in the list were not
finished, because of this it will repeat 5 echo statements. for e.g. Now try script as follows
$ cat > mtable #!/bin/sh # #Script to test for loop # # if [ $# -eq 0 ] then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo " Use to print multiplication table for given number"
exit 1
Linux 25
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
fi n=$1 for i in 1 2 3 4 5 6 7 8 9 10
do echo "$n * $i = `expr $i \* $n`" done
while [ condition ]
do
command1
command2
command3
..
....
done
Loop is executed as long as given condition is true. For eg. Above for loop program can be
written using while loop as
$cat > nt1 #!/bin/sh # #Script to test while statement # # if [ $# -eq 0 ] then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo " Use to print multiplication table for given number"
exit 1
Linux 26
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
case $variable-name in
pattern1) command
...
..
Linux 27
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
command;;
pattern2) command
...
..
command;;
patternN) command
...
..
command;;
*) command
...
..
command;;
esac
The $variable-name is compared against the patterns until a match is found. The shell then
executes all the statements up to the two semicolons that are next to each other. The
default is *) and its executed if no match is found. For eg. Create script as follows
$ cat > car # # if no vehicle name is given # i.e. -z $1 is defined and it is NULL # #
if no command line arg
if [ -z $1 ] then
rental="*** Unknown vehicle ***" elif [ -n $1 ] then # otherwise make first
arg as rental
rental=$1 fi
case $rental in "car") echo "For $rental Rs.20 per k/m";; "van") echo "For $rental
Rs.10 per k/m";; "jeep") echo "For $rental Rs.5 per k/m";; "bicycle") echo
"For $rental 20 paisa per k/m";; *) echo "Sorry, I can not gat a $rental for
you";;
esac
Linux 28
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
(12)The read Statement Use to get input from keyboard and store them to variable.
Syntax: read varible1,
varible2,...varibleN Create script
as
$ cat > sayH # #Script to read your name from key-board # echo "Your first name
please:" read fname echo "Hello $fname, Lets be friend!"
Run it as follows
$ chmod +x sayH $ ./sayH
This script first ask you your name and then waits to enter name from the user, Then
user enters name from keyboard (After giving name you have to press ENTER key) and
this entered name through keyboard is stored (assigned) to variable fname.
* Matches any string or group of characters.For e.g. $ ls * , will show all files, $ ls a* - will
show all files whose first name is starting with letter 'a', $ ls *.c ,will show all files having
extension .c $ ls ut*.c, will show all files having extension .c but first two letters of file
name must be 'ut'.
/bin/arch /bin/awk
/bin/ash /bin/basename
/bin/ash.static /bin/bash
/bin/bsh /bin/chmod /bin/cp
/bin/cat /bin/chown /bin/cpio
/bin/chgrp /bin/consolechars /bin/csh
But
Linux 29
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
$ ls /bin/[!a-o] $ ls /bin/[^a-o]
If the first character following the [ is a ! or a ^ then any character not enclosed is
matched i.e. do not show us file name that beginning with a,b,c,e...o, like
/bin/ps /bin/rvi
/bin/pwd /bin/rview
/bin/red /bin/sayHello
/bin/remadmin /bin/sed
/bin/rm /bin/setserial
/bin/rmdir /bin/sfxload
/bin/rpm /bin/sh
/bin/sleep /bin/touch /bin/view
/bin/sort /bin/true /bin/wcomp
/bin/stty /bin/umount /bin/xconf
/bin/su /bin/uname /bin/ypdomainname
/bin/sync /bin/userconf /bin/zcat
/bin/tar /bin/usleep
/bin/tcsh /bin/vi
Linux 30
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
We can copy old shell's variable to new shell (i.e. first shells variable to seconds shell), such
variable is know as Global Shell variable. To do this use export command Syntax: export
variable1, variable2,.....variableN For e.g.
$ vech=Bus $ echo $vech
Bus
$ export vech $ /bin/bash $ echo $vech
Bus
$ exit $ echo $vech
Linux 31
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
command2 is executed if and only if command1 returns a non-zero exit status. You can use
both as follows command1 && comamnd2 if exist status is zero || command3 if exit status
is non-zero Here if command1 is executed successfully then shell will run command2 and if
command1 is not successful then command3 is executed. For e.g.
$ rm myf && echo File is removed successfully || echo File is not removed
If file (myf) is removed successful (exist status is zero) then "echo File is removed
successfully" statement is executed, otherwise "echo File is not removed" statement is
executed (since exist status is non-zero)
By default in Linux every program has three files associated with it, (when we start our
program these three files are automatically opened by your shell) The use of first two files
(i.e. stdin and stdout) , are already seen by us. The last file stderr (numbered as 2) is used
by our program to print error on screen. You can redirect the output from a file descriptor
directly to file with following Syntax: file-descriptor-number>filename For e.g.
$ rm bad_file_name111
rm: cannot remove `bad_file_name111': No such file or directory ,is the output
(error) of the above program. Now if we try to redirect this error-output to file, it can
not be send to file
$ rm bad_file_name111 > er
Linux 32
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Still it prints output on stderr as rm: cannot remove `bad_file_name111': No such file or
directory, And if you see er file as $ cat er , This file is empty, since output is send to error
device and you can not redirect it to copy this error-output to your file 'er'. To overcome
this we have to use following command
$ rm bad_file_name111 2>er
Note that no space are allowed between 2 and >, The 2>er directs the standard error
output to file. 2 number is default number of stderr file. Now consider another example,
here we are writing shell script as follows
$ cat > demoscr
if [ $# -ne 2 ]
then
echo "Error : Number are not supplied"
echo "Usage : $0 number1 number2"
exit 1
fi
ans=`expr $1 + $2`
echo "Sum is $ans" Try it as follows
$ chmod +x demoscr
$ ./demoscr
Here for first sample run , our script prints error message indicating that we have not
given two number. For second sample run, we have redirect output of our script to file,
since it's error we have to show it to user, It means we have to print our error message on
stderr not on stdout. To overcome this problem replace above echo statements as follows
echo "Error : Number are
not supplied" 1>&2 echo
"Usage : $0 number1
number2" 1>&2
Now if you run as $ ./demoscr > er1 Error : Number are not supplied Usage : ./demoscr
number1 number2 It will print error message on stderr and not on stdout. The 1>&2 at the
end of echo statement, directs the standard output (stdout) to standard error (stderr)
device. Syntax: from>&destination
Functions
Function is series of instruction/commands. Function performs particular activity in shell. To
define function use following Syntax:
function-name ( )
Linux 33
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
{
command1
command2
.....
...
commandN
return
Where function-name is name of you function, that executes these commands. A return
statement will terminate the function. For e.g. Type SayHello() at $ prompt as follows
$ SayHello()
{
echo "Hello $LOGNAME, Have nice computing"
return
}
Save the file and exit it, after all this modification your file may look like as follows
Linux 34
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
# /etc/bashrc
# System wide
functions and aliases #
Environment stuff goes
in /etc/profile
# # today() to print formatted date # # To run this function type today at the $
prompt # Added by Vivek to show function in Linux today() { echo This is a `date
+"%A %d in %B of %Y (%r)"` return }
To run function first completely logout by typing exit at the $prompt (Or press CTRL + D,
Note you may have to type exit (CTRL +D) twice if you login to root account by using su
command) ,then login and type $ today , this way today() is available to all user in your
system, If you want to add particular function to particular user then open .bashrc file in
your home directory as follows
# vi .bashrc OR # mcedit .bashrc
At the end of file add following in .bashrc file
SayBuy()
{ echo "Buy $LOGNAME ! Life never be the same, until you log again!" echo "Press
a key to logout. . ." read return
}
Save the file and exit it, after all this modification your file may look like as follows
SayBuy()
{ echo "Buy $LOGNAME ! Life never be the same, until you log again!" echo "Press
a key to logout. . ." read return
}
To run function first logout by typing exit at the $ prompt (Or press CTRL + D ) ,then
logon and type $
SayBuy , this way SayBuy() is available to only in your login and not to all user in system,
Use .bashrc
file in your home directory to add User specific aliases and functions only. (Tip: If you want
Linux 35
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
to show some
message or want to perform some action when you logout, Open file .bash_logout in your
home directory
and add your stuff here For e.g. When ever I logout, I want to show message Buy! Then
open your
.bash_logout file using text editor such as vi and add statement
$ cat > menuui # # Script to create simple menus and take action according to
that selected # menu item # while : do
clear
echo "-------------------------------------"
echo " Main Menu "
echo "-------------------------------------"
echo "[1] Show Todays date/time"
echo "[2] Show files in current directory"
Linux 36
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
case $yourch in 1) echo "Today is `date` , press a key. . ." ; read ;; 2) echo
"Files in `pwd`" ; ls -l ; echo "Press a key. . ." ; read ;; 3) cal ; echo "Press
a key. . ." ; read ;; 4) vi ;; 5) exit 0 ;; *) echo "Opps!!! Please select choice
1,2,3,4, or 5";
echo "Press a key. . ." ; read ;;
esca
done
Above all statement explained in following table
Linux 37
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
User interface usually includes, menus, different type of boxes like info box, message box,
Input box etc. In Linux shell there is no built-in facility available to create such user
interface, But there is one utility supplied with Red Hat Linux version 6.0 called dialog,
which is used to create different type of boxes like info box, message box, menu box, Input
box etc. Now try dialog utility as follows :
$ cat > dia1
dialog --title "Linux Dialog Utility Infobox" --backtitle "Linux Shell Script\
Tutorial" --infobox "This is dialog box called infobox, which is used\
to show some information on screen, Thanks to Savio Lam and\
Stuart Herbert to give us this utility. Press any key. . . " 7 50 ; read
Linux 38
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
esac
Linux 39
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Above script creates yesno type dialog box, which is used to ask some questions to the user
, and answer to those question either yes or no. After asking question how do we know,
whether user has press yes or no button ? The answer is exit status, if user press yes
button exit status will be zero, if user press no button exit status will be one and if user
press Escape key to cancel dialog box exit status will be one 255. That is what we have
tested in our above shell as inputbox using dialog utility
sel=$?
na=`cat
/tmp/in
put.$$`
case
$sel in
esac rm -f /tmp/input.$$
Inputbox is used to take input from user, Here we are taking Name of user as input. But
where we are going to store inputted name, the answer is to redirect inputted name to file
via statement 2>/tmp/input.$$ at the end of dialog command, which means send screen
output to file called /tmp/input.$$, letter we can retrieve this inputted name and store to
variable as follows na=`cat /tmp/input.$$`. For inputbox exit status is as follows
Linux 40
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Now we will write script to create menus using dialog utility, following are menu items
Date/time Calendar Editor and action for each menu-item is follows
MENU-ITEM ACTION
Date/time Show current date/time Calendar Show calendar Editor Start vi Editor
menuitem=`cat /tmp/menuitem.$$`
opt=$?
rm -f /tmp/menuitem.$$
Linux 41
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
After creating menus, user selects menu-item by pressing enter key the selected choice is
redirected to temporary file, Next this menu-item is retrieved from temporary file and
following case statement compare the menu-item and takes appropriate step according to
selected menu item. As you see, dialog utility allows more powerful user interaction then
the older read and echo statement. The only problem with dialog utility is it work slowly.
trap command
Now consider following script
$ cat > testsign ls -R /
if [ ! -f $filename ]; then echo "Sorry, $filename does not exit, Creating $filename
database" echo "Appointment Note keeper Application database file" >
$filename
Linux 42
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
fi
echo "Data entry start data: `date`" >/tmp/input0.$$ # # Set a infinite loop #
while : do
echo -n "Appointment Title:"
read na
echo -n "Appoint time :"
read ti
echo -n "Any Remark :"
read remark
echo -n "Is data okay (y/n) ?"
read ans
fi
fi done }
Linux 43
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
$ ls /tmp/input*
Our script needs to detect when such signal (event) occurs, To achieve this we have to first
detect Signal using trap command Syntax: trap {commands} {signal number list}
To catch this signal in above script, put trap statement before calling Take_input1 function
as trap del_file 2 ., Here trap command called del_file() when 2 number interrupt (
i.e.CTRL+C ) occurs. Open above script in editor and modify it so that at the end it will look
like as follows
$ vi testsign1
or
$ mcedit testsign1 # # signal is trapped to delete temporary file , version 2 #
del_file() {
echo "* * * CTRL + C Trap Occurs (removing temporary file)* * *"
rm -f /tmp/input0.$$
exit 1
Take_input1()
{ recno=0 clear echo "Appointment Note keeper Application for Linux" echo -n
"Enter your database file name : " read filename
if [ ! -f $filename ]; then echo "Sorry, $filename does not exit, Creating $filename
database" echo "Appointment Note keeper Application database file" >
$filename
fi
echo "Data entry start data: `date`" >/tmp/input0.$$ # # Set a infinite loop #
while : do
echo -n "Appointment Title:"
read na
echo -n "Appoint time :"
read ti
echo -n "Any Remark :"
read remark
echo -n "Is data okay (y/n) ?"
read ans
Linux 44
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
fi
fi done }
# # Set trap to for CTRL+C interrupt, # When occurs it first it calls del_file() and
then exit # trap del_file 2
getopts command
This command is used to check valid command line argument passed to script. Usually used
in while loop. Syntax: getopts {optsring} {variable1}
getopts is used by shell to parse command line argument. optstring contains the option
letters to be recognized; if a letter is followed by a colon, the option is expected to have an
argument, which should be separated from it by white space. Each time it is invoked,
getopts places the next option in the shell variable variable1, When an option requires an
argument, getopts places that argument into the variable OPTARG. On errors getopts
diagnostic messages are printed when illegal options or missing option arguments are
encountered. If an illegal option is seen, getopts places ? into variable1. For e.g. We have
script called ani which has syntax as ani -n -a -s -w -d Options: These are optional
argument
-n name of animal -a age of animal -s sex of animal -w weight of animal -d
Linux 45
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
See because of getopts, we can pass command line argument in different style.
Following are invalid options for ani script
$ ani -nLassie -a4 -sFemal -w20Kg
Linux 46
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Q.1. How to write shell script that will add two nos, which are supplied as command line
argument, and ifthis two nos are not given show error and its usage Answer: See Q1 shell
Script.
Q.2.Write Script to find out biggest number from given three nos. Nos are supplies as
command line
argument. Print error if sufficient arguments are not supplied.
Answer: See Q2 shell Script.
Q.6.Write script to print given number in reverse order, for eg. If no is 123 it must print as
321.
Answer: See Q6 shell Script.
Q.7.Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all
digit will be
1+2+3 = 6.
Answer: See Q7 shell Script.
Linux 47
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Q.11.Write script to determine whether given file exist or not, file name is supplied as
command line
argument, also check for sufficient number of command line argument
Answer: See Q11 shell Script.
Q.12.Write script to determine whether given command line argument ($1) contains "*"
symbol or not, if
$1 does not contains "*" symbol add it to $1, otherwise show message "Symbol is not
required". For e.g.
If we called this script Q12 then after giving ,
$ Q12 /bin
Here $1 is /bin, it should check whether "*" symbol is present or not if not it should
print Required i.e. /bin/*, and if symbol present then Symbol is not required must be
printed. Test your script as
$ Q12 /bin $ Q12 /bin/*
Answer: See Q12 shell Script
1. Q.13. Write script to print contains of file from given line number to next given
number of lines. For e.g. Ifwe called this script as Q13 and run as
$ Q13 5 5 myf , Here print contains of 'myf' file from line number 5 to next 5 line of that
file.
Answer: See Q13 shell Script
2. Q.14. Write script to implement getopts statement, your script should understand
following command lineargument called this script Q14,
Q14 -c -d -m -e
Where options work as
-c clear the screen
-d show list of files in current working directory
-m start mc (midnight commander shell) , if installed
-e { editor } start this { editor } if installed
Answer: See Q14 shell Script
Linux 48
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
3. Q.15. Write script called sayHello, put this script into your startup file called
.bash_profile, the scriptshould run as soon as you logon to system, and it print any one of
the following message in infobox using
dialog utility, if installed in your system, If dialog utility is not installed then use echo
statement to print
message : -
Good Morning
Good Afternoon
Good Evening , according to system time.
Answer: See Q15 shell Script
4. Q.16. How to write script, that will print, Message "Hello World" , in Bold and Blink
effect, and in differentcolors like red, brown etc using echo command.
Answer: See Q16 shell Script
5. Q.17. Write script to implement background process that will continually print
current time in upper right
6. Q.18. Write shell script to implement menus using dialog utility. Menu-items and
action according to selectmenu-item is as follows
Note: Create function for all action for e.g. To show date/time on screen create function
show_datetime().
Answer: See Q18 shell Script.
Q.19. Write shell script to show various system configuration like1) Currently logged user
and his logname 2) Your current shell 3) Your home directory 4) Your operating system type
5) Your current path setting 6) Your current working directory 7) Show Currently logged
number of users 8) About your os and version ,release number , kernel version 9) Show all
available shells 10) Show mouse settings 11) Show computer cpu information like processor
type, speed etc 12) Show memory information 13) Show hard disk information like size of
hard-disk, cache memory, model etc 14) File system (Mounted) Answer: See Q19 shell
Linux 49
No.3, II Floor, 100 Feet Ring Road BTM Layout II Stage Bangalore‐560076. Website: www.proximo.in
Script.
Linux 50