Linux Shell Programming
Linux Shell Programming
Command Interpreters
Shells are used for direct user interaction and for smaller
programming tasks or shell scripts
Linux Shells
Command Separators
NEWLINE ('\n' )
Semicolon(;)
Shell
interprets the shell scripts, executes
the commands in the script sequentially
Startup files
Eg
chmod u+x file1.c
chmod u+x, g+x file1.c
chmod a+x file1.c
chmod u+x,g+x file1.c
chmod --reference=file1 file2
chmod -R u+x dir1
chmod 755 file1
chmod 111 file1
chmod 777 file1
chmod
STICKY bit
Sticky Bit is mainly used on folders in order to avoid
deletion of a folder and its content by other users
though they having write permissions on the folder
contents. If Sticky bit is enabled on a folder, the
folder contents are deleted by only owner who
created them and the root user.
touch file1.txt
touch -t [[CC]YY]MMDDhhmm[.ss]
touch -t 200101011200.09 file1.txt
touch -t 01011200 file1.txt
tput and stty
tput cols // no of colums
tput lines // no of rows in given terminal
tput cup 2 2 // move curser to 1, 1 position
tput bold
tput smul // set under line
tupt rmul // remove underline
date +%d %B %Y
date -s "27 September 2013 14:53:22"
date and time contd..
start=$(date +%s)
sleep 3
end=$(date +%s)
difference=$(( end - start))
echo Time taken to execute commands is $difference
seconds.
cal
cal
cal 10 2014
cal 2014
mm=10; yy=2014
cal $mm $yy
cal -3
cal -m3 // for given month
grep command
not r
-------
ls -l | grep ^- // display only regular files
entry
ls -l | grep ^d // display only directory files
grep command
Example:
#!/bin/bash
( Shebang is a line for which #! is prefixed to the
interpreter path. /bin/bash is the interpreter
command path for Bash.)
Exercise:
sh shellfile
. shellfile
./shellfile
shellfile
bash shellfile
source shellfile
ksh/zsh/tcsh shellfile
Exercise:
ignoreeof (disable CTRL-D logout)
noclobber ( dont overwirte files through
redirection)
noglob ( disable special characters used for
filename expansion: *,?,~,and [ ].)
Keywords:
I/O
redirection - change where processes
read from and write to.
Positional
parameters command name
and arguments, refer to them by their
position on the command line Eg: $1-$9
Special
parameters $ with a special
character
$# number of arguments
$* list of arguments $1 $2 $2
$@ list of arguments $1 $2 $3
$$ PID of current shell
$? exit status of the last executed
command
$! pid of the last command executed in
the background
$0 name of script
var=cdac
echo $var
var=cdac acts
echo $var
echo ${var}
year=2013
echo "Hello world $year"
echo Hello world $year
echo 'Hello world $year'
echo cont..
echo -e "1\t2\t3"
(-) infront of bash indicates this shell was started by the login process
Exercise:
sleep 50 &
sleep 60 &
fg %1
jobs
kill %1
sleep 50 ( press ctrl + z )
bg ( above proces will become a bg job)
Exercise:
ps -lax
pstree
ps -e -o cmd,pid,ppid,pri,ni,class
man ps
Kill pid-no
Kill -9 pid
Metacharacters
Type Metacharacters
Filename ? * [] [!...]
substitution
I/O redirection > < >> <<
Process ; () & && ||
Quoting \ ``
metacharacter
s
Positional $1.$9
parameters
Special $0 $* $@ $# $! $$
characters
Filename Substitution Metacharacters
Examples:
ls * Lists all files all
ls *.* List all files having ext
ls b* Lists all files beginning with character b
ls ?? Lists all files whose names are 2 characters long
ls e?f? Lists all 4 character filenames whose first
character is e and third character is f
ls [abd]* Lists all files whose first character is a, b or
d
ls [^abd]* Lists all files whose first character is not a, b
or d
ls [c-fmrv-z]* Lists all files whose first character is m or r
or is in the range c to f or v to z
ls [!c-j]* Lists all files whose first character is anything
other than an alphabet in the range c to j
I/O Redirection Metacharacters
NOTE:
Example:
echo $, \, ?,*, this is india!
$, \, ?,*, this is india!
Quoting Metacharacters (Contd)
The
back quotes ` ` replace the
command they enclose with its output.
Example:
echo Today is `date`
Today is Sun Nov 26 16:16:14 IST 2006
Quoting Metacharacters (Contd)
Example:
bash $ name=ACTS
bash $ echo Your college name is $name
Your college name is ACTS
Command Line Expansion (Contd)
Command Substitution
- Use standard output of a command
$(command) or `command`
winner=dylan
result=The name is the $winner variable
echo $result
Exercise:
winner=dylan
result=$winner won \$100.00
echo $result
Command name/filename completion
z=($x+$y); or z=$x+$y;
let var1+=5
let var1-=1
let var1=10
let var2=20
let result=$[var1 + var2]
let result=$[var1 + 5]
Array
arr=(10 20 30 40 50)
or
arr[0]=10 arr[1]=20 arr[2]=30
arr[3]=40 arr[4]=50
echo ${arr[1]}
index=2
echo ${arr[index]}
declare -A money_exc
money_exc=([USdollar]=62 [AUSdollar]=50)
fun2() {
res = $(( $1 + $2 ))
echo result is $res
}
fun2 100 200 // function call with parameter
Funtion contd..
fun3( ) {
printf in function call
sleep 1
fun3
}
Export -f fun3
Try command
type fun_name
Funtion contd..
fun5()
{
res=$(($1 + $2))
echo "res is $res"
return $res
}
. ./shellprog
when a script executes an external command or
script, a new environment (a subshell) is cre ated,
the command is executed in the new environment,
and the environment is then discarded
Same thing can be achived by
source shellprog
Variables
Example
#!/bin/bash
STR=Hello World!
echo $STR
PATH=$PATH:/home/guest/bin
export PATH
PS1= '\t \W '
PS1 ='\t \h '
PS1 ='\t \W \$'
The read command
Example
#!/bin/bash
echo -n Enter name of file to delete:
read file
echo Type 'y' to remove it, 'n' to change your mind ...
rm -i $file
echo "That was YOUR decision!
Entering and Displaying Values
clear
echo
echo -n "Enter a number: "
read num
if [ $num -eq 0 ]
then
echo "The number entered by you is zero"
elif [ $num -lt 0 ]
then
echo "The number entered by you is negative"
else
echo "The number entered by you is positive"
fi
Expressions
An expression can be: String comparison, Numeric comparison,
File operators and Logical operators and it is represented by
[expression]:
String Comparisons:
= compare if two strings are equal
!= compare if two strings are not equal
-n evaluate if string is not null
-z evaluate if string is null
Examples:
[ $var1 = $var2 ] (true if var1 same as var2, else false)
[ $var1 != $var2] (true if var1 not same as var2, else false)
[ -n $var1 ] (true if var1 has a length greater then 0, else
false)
[ -z $var2 ] (true if var2 has a length of 0, otherwise false)
Expressions
vi test3.sh
clear
echo
echo -n "Enter two names: "
read name1 name2
if [ $name1 = $name2 ]
then
echo "The names entered by you are the same"
else
echo "The names are different"
fi
Expressions (Contd.)
Files operators:
-d check if path given is a directory
-f check if path given is a file
-e check if file exists
-r check if read permission is set for file or directory
-s check if a file has nonzero size
-w check if write permission is set for a file or directory
-x check if execute permission is set for a file or directory
Examples:
[ -d $fname ] (true if fname is a directory, otherwise false)
[ -f $fname ] (true if fname is a file, otherwise false)
[ -e $fname ] (true if fname exists, otherwise false)
[ -s $fname ] (true if fname size is nonezero, else false)
[ -r $fname ] (true if fname has the read permission, else false)
[ -w $fname ] (true if fname has the write permission, else
false)
[ -x $fname ] (true if fname has the execute permission, else
false)
Expressions (Contd.)
More Files operators:
-h check if given file is symbolic file
-b check if given file is block special device file
-c check if given file is character special device file
-p check if given file is named pipe file
-S check if given file is socket file
-O check if you own this file
-G check if group id of file same as current user
vi test4.sh
clear
echo
echo -n "Enter the name of a directory: "
read dir_name
if [ -d $dir_name ]
then
echo $dir_name is a directory
else
echo $dir_name is a file
fi
echo
case Statement
Used to execute statements based on specific values. Often
used in place of an if statement if there are a large number of
conditions.
Value used can be an expression
each set of statements must be ended by a pair of semicolons;
a *) is used to accept any value not matched with list of values
case $var in
val1)
statements;;
val2)
statements;;
*)
statements;;
esac
Example
vi test5.sh
clear
echo
echo -n Enter a number 1 < x < 10:
read x
case $x in
1) echo Value of x is 1.;;
2) echo Value of x is 2.;;
3) echo Value of x is 3.;;
4) echo Value of x is 4.;;
5) echo Value of x is 5.;;
6) echo Value of x is 6.;;
7) echo Value of x is 7.;;
8) echo Value of x is 8.;;
9) echo Value of x is 9.;;
0 | 10) echo wrong number.;;
*) echo Unrecognized value.;;
esac
echo
Iteration Statements
The for structure is used when you are looping through a range
of variables
for var in list
do
statements
done
statements are executed with var set to each value in the list.
vi test6.sh
clear
echo
sum=0
for num in 1 2 3 4 5
do
sum=`expr $sum + $num`
done
echo The sum is: $sum
echo
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n "$i"
done
done
Iteration Statements (Contd.)
vi test7.sh
for x in paper pencil pen; do
echo The value of variable x is: $x
sleep 1
done
if the list part is left off, var is set to each parameter passed to
the script ( $1, $2, $3,)
vi test8.sh
for x
do
echo The value of variable x is: $x
sleep 1
done
./test8.sh eena meena deeka
while Statement
The while structure is a looping structure. Used to execute a set of
commands while a specified condition is true. The loop terminates as
soon as the condition becomes false. If condition never becomes false,
loop will never exit.
while expression
do
statements
done
vi test9.sh
clear
echo
echo -n "Enter a number: "; read x
sum=0; i=1
while [ $i -le $x ]; do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo
echo "The sum of the first $x numbers is: $sum"
echo
Menu example
clear ; loop=y
while [ $loop = y ] ; do
echo Menu; echo ====
echo D: print the date
echo W: print the users who are currently log on.
echo P: print the working directory
echo Q: quit.
echo
read s choice
case $choice in
D | d) date ;;
W | w) who ;;
P | p) pwd ;;
Q | q) loop=n ;;
*) echo Illegal choice. ;;
esac
echo
done
continue Statement
The continue command causes a jump to the next iteration
of the loop, skipping all the remaining commands in that
particular loop cycle.
vitest10.sh
clear
echo
LIMIT=19
echo
echo "Printing Numbers 1 through 20 (but not 3 and 11)"
a=0
while [ $a -le $LIMIT ]; do
a=`expr $a + 1`
if [ $a -eq 3 ] || [ $a -eq 11 ]
then
continue
fi
echo -n "$a "
done
echo
echo
break Statement
ln original-file added-file
ln file1 file2
Exercise: Tar
tar cvf mytarfile.tar mydir
tar xvf mytarfile.tar
gzip gunzip
bzip2 bunzip2
xz unxz
File Extension:
.rpm ( redhat pakage manger file )
.tz ( tar with compress )
.Z ( compress )
.bin ( self extracting software file )
.deb ( debian linux package )
RPM:
Rpm --install --verbose --hash --test sw.rpm
Rpm -ivh sw.rpm
Rpm -q sw
Rpm -e sw
Rpm -V bash
Rpm -Va
Some Tips
sed -e 's/[0-9]//g'
case $char in
[0-9]) echo "$char is Number/digit" ;;
[[:upper:]]) echo "$char is UPPER character" ;;
[a-z]) echo "$char is lower character" ;;
*) echo "$char is Special symbol" ;;
echo {1..9}
echo {a..z}
echo {A..Z}
seq
seq 1 10
seq 1 2 10
seq 10 -1 1
seq 10 -2 1
head and tail command
head file.txt
head -n 5 file.txt
head -n -5 file.txt // print all excluding last 5 lines
tail file.txt
tail -n 5 file.txt
tail -n +5 file.txt // print all excluding first 5 lines
bc
echo 100.25+200.50 | bc
echo sqrt(99) | bc
echo sqrt(99) | bc -l
echo scale=2;sqrt(99) | bc
var1=99 ; echo scale=2; sqrt($var1) | bc
#!/bin/bash
var1=$1
length=`echo ${#var1}`
while [ $length -ne 0 ]
do
temp=$temp`echo $var1 | cut -c $length`
((length--))
done
echo $temp
------------------------------------------
Need to explore temp=$temp and cut command
Eg. Revese String
To understand how temp=$temp works
var2=56
var1=$var1`echo $varr2` // with help of command
var1=cdac
var2=acts
var1=$var1$var2
Eg. Revese String
var1=$1
temp=`echo $var1 | rev`
echo $temp
str=acts
i=0
while [ $i -lt ${#str} ]
do
arr[$i]=${str:$i:1}
let ++i
done
echo ${arr[2]}
echo ${arr[*]}
Awk
ret=$(function)
echo $ret
function()
{
var=256;
echo 3;
return $var;
}
ret=$(function)
echo $ret
echo $?
BACKUP_FOLDER_NAME="BACKUP_"$(date +%d_%m_
%Y_%H_%M_%S)
mkdir $BACKUP_FOLDER_NAME
Exercise: File operation
chown username filename
chown -R username filename