SH 2
SH 2
SH 2
--------------------------
in commandline -> bash -x filename.sh ->(1)
set -x
..
..
set +x
---------------------------------------------------------------------------
Logical operators
--------------------
|->In Single conditional statement,test more than one condition
----------------------------- ======================== //use logical
operator
example:
----------
test port number 501-599
test your working shell is sh (or) bash anyshell is matched ->OK
|
test your hostname and kernel
| |
------ --------
host01 host02 | |
Sunos Linux
port=550
--------------
logical or => -o
---
Condition1 Condition2 Result
True True True
True False True
False True True
False False False
sh_var="sh"
if [ $name == "admin" ]
then
there is no action
else
echo "Sorry your not admin"
fi
Vs
if ! [ $name == "admin" ]
then
echo "Sorry your not admin"
fi
----------------------------------------------------------------------------
Write a shell script
-----------------------------------------------------------------------------------
-----------
[ `whoami` == "root" -a `hostname` == "host01" -a `ps -e|wc -l` -gt 100 -a $p ==
"xend" ]
---------------- -------------------- --------------------
------------
[[ `whoami` == "root" && `hostname` == "host01" ]] && [[ `ps -e|wc -l` -gt 100 &&
$p == "xend" ]]
if [[ `whoami` == "root" && `hostname` == "host01" ]] && [[ `ps -e|wc -l` -gt 100
&& $p == "xend" ]]
then
....
else
....
fi
[[ 100 -gt 50 && "abc" == "abc" ]] && [[ 560 -gt 500 && 600 -eq 600 ]]
# [ 100 -gt 50 -a "abc" == "abc" -a 560 -gt 500 -a 600 -eq 600 ]
#echo $?
0
#[ 100 -gt 50 -a "abc" == "abc" ] -a [ 560 -gt 500 -a 600 -eq 600 ]
bash: [: too many arguments
#
#[[ 100 -gt 50 && "abc" == "abc" ]] && [[ 560 -gt 500 && 600 -eq 600 ]]
#echo $?
0
#sh_var="ksh"
#
#[[ $sh_var == "bash" || $sh_var == "ksh" ]]
#echo $?
0
#[ $sh_var == "bash" -o $sh_var == "ksh" ]
#echo $?
0
#[[ 100 -gt 50 && "abc" == "Abc" ]] && [[ 560 -gt 500 && 600 -eq 600 ]]
#echo $?
1
-----------------------------------------------------------------------------------
----------------------------------------------
recap
-----
-> arithmetic
-> relational
-> logical
|
-> file test operators
--------------------
|-> file types
|-> file mode (operation) - read(-r) write(-w) execute(-x)
file types
------------
1. Regular file (or) Ordinary file (-f)
ASCII / Text - user can able to read/understand (ex: p1.sh p1.java p1.c
p1.log etc.,)
ELF - user can't able to read/understand (ex: unix/linux commands)
2. Directory file (-d)
3. Link file (or) symbolic link (or) soft link ln -s source target (-l (or) -h)
[<space>FileTestOperator<space>inputFile<space>]
if [ -f filename ]
then
....
else
....
fi
if [ -x filename ]
then
...
else
...
fi
[ -e /etc ]
echo $? ------>0
[ -e /etc/passwd ]
echo $? -------------->0
[ -e pop.log ]
echo $? ------------>1
______________________________________________________________________
Q. Write a shell script
if [ -e $fname ]
then
if [ -f $fname ]
then
echo "File: $fname is a reg.file"
ls -l $fname
elif [ -d $fname ]
then
echo "File: $fname is a directory file"
ls -ld $fname
else
echo "File:$fname is exists"
file $fname
fi
else
echo "Sorry file $fname is not exists"
exit
fi
if [ -d $dname ]
then
echo "directory $dname is exists"
ls -ld $dname
else
mkdir $dname
if [ $? -eq 0 ]
then
echo "Directory $dname is created"
ls -ld $dname
else
echo "Directory $dname creation is failed"
fi
fi
-----------------------------------------------------------------------------------
--------
case statement
--------------
|-> Code block
|-> execute only one time
Syntax:-
---------
case value in
pattern1) pattern1 operation
;;
pattern2) pattern2 operation
;;
pattern3) pattern3 operation
;;
..
patternN) patternN operation
;;
*) default operation
esac
Note: if..elif with == (or) -eq operator logic is same as case statement
server="Linux"
-------------------------------------------------------------------
if [ condition ]
then
case $variable in
pattern1) .. ;;
pattern2) .. ;;
..
*) ...
esac
else
....
fi
case $variable in
pattern1) if [ condition ]
then
...
else
...
fi
;;
pattern2) if [ condition1 ]
then
...
elif [ condition2 ]
then
..
..
else
..
fi
;;
..
*) ....
esac
-----
write a shell script
---------------------
step 1: create a menu list in below format (use - echo with multiline string)
step 3:
gcc => read a compiler version from <STDIN>
test version 4-6
|
shell name =>read a shell name from <STDIN>
test shell is sh (or) ksh (or) bash //any one shell is matched
|
App => read a port number from <STDIN>
test a port number 1001-1999
|
system info => display kernel version,login name,hostname,Today date
echo "
if [ condition ]
then if [ condition ];then
... ....
else => else
... ....
fi fi
===================================================================================
==========================
Looping statements
-------------------
|->Code block - execute more than one time.
...................
conditional statement Vs looping statement
- if,case while,for,until,select
------------------------------------------------------------------------
- in shell script looping statements
Rule 1: initialization 0 15
|
Rule 2: test the condition 5 -> 0 to 5 15 ... 0
|
Rule 3: arithmetic increment(add-expr) decrement(sub-expr)
Syntax:-
---------
initialization
while [ condition ]
do
code block
arithmetic operation
done
i=0
while [ $i -lt 5 ]
do
uptime;sleep 2
i=`expr $i + 1` # ((i++))
done
-------------------------------------------------------------------------
i=`expr $i + 1`
done
-------------------------------------------------------------------------------
while<space>:
do
code block <== always active
done
(or)
while true
do
Code block
done
-----------------------------------------------------
until
------
-> opp.while loop
|
-> until loop - test the condition ->True ->won't execute the code block
|
|----->False -> execute the code block
until [ condition ]
do
code block
..
done
|
same as
|
while ! [ condition ]
do
....
done
-----------------------------------------------------------------------------------
Syntax:-
----------
for variable in <collection of items>
do
code block
done
for v in 10 1.45 data /etc/passwd 127.0.0.1 <== each item separated by space
do
echo "v value is:$v" <== code block
done
v value is:10
v value is:1.45
v value is:data
v value is:/etc/passwd
v value is:127.0.0.1
Hello...data1
Hello...data2
Hello...data3
Expected result
----------------
Enter a pin number:1932
Success pin is matched - at 1
Enter a pin number:3433
Enter a pin number:1932
Success pin is matched - at 2
_______________________________________________________________________________
Q2. Write a shell script
command >newfile
--------
|
create/write
command >>newfile
--
|->append operation - won't overwrite existing file
c=0
while [ $c -lt 5 ]
do
uptime
c=`expr $c + 1`
done >result.log
|------------
---------------------------------------------------------------------------
Q3. Write a shell script
|
step 1: create two directories (mkdir reg_file dirs)
|
step 2: using for loop - iterate list of files
tar
---
-> create a tar file -> cf =>cvf
-> list a tar file -> tf =>tvf
-> extract a tar file -> xf =>xvf
ex:-
------
root@krosumlabs:~/ShellScript_Training# tar -cvf B1.tar *.sh Demo/ Dx/ Dy/ chat
p10.sh
p11.sh
p12.sh
p13.sh
p14.sh
p15.sh
p16.sh
p17.sh
p18.sh
--------------------------------------------------------------------------------
select loop
-----------
|-> Collection style loop
|-> menu driven
|-> always active
|-> #? prompt
|-> syntax like for loop style
Syntax:-
--------
select variable in <list of menu items>
do
code block
done
select + case
------ =====
| |->conditional code
loop
-----------------------------------------------------------------
prompt => primary prompt => username@hostname <workingdir>]#
secondary prompt
------------------
root@host~]# echo "one
>two
>three
>four
>five"
|
secondary prompt
PS2
----------
while :
do
echo "
done
========================================================================
|
modify the above code - use select loop - demonstrate menu driven programming
===================================================================================
=
mkdir Temp
cd Temp
| |
count=0
..
>"r$count".log
------
c=0
while [ $c -lt 5 ]
do
uptime;sleep 3
date;sleep 2
ps;sleep 1
c=`expr $c + 1`
done >r1.txt
command >resultfile
-------
|
execute
|
then - write to file
Vs
c=0
while [ $c -lt 5 ]
do
uptime >>LB.log ; sleep 3
date >D1.log ; sleep 2
ps >>p1.log ; sleep 1
c=`expr $c + 1`
done
|
after finished loop execution
open LB.log file - will get 5entries of uptime result
--
open D1.log file - will get only one entry of date command result
----------------
==================================================================================
Commandline arguments
______________________
->Runtime inputs
|
->non-interactive inputs
|
->in shell script commandline arguments are called positional parameters
--------------
file: p1.sh
-------------
read -p "Enter a IP Address:" IP <== interactive input(or) execution input
read -p "Enter a count value:" count <== interactive input(or) execution input
-------------------------------------------
root@host~]# ./p1.sh {Enter}
Enter a IP Address:
|
cronjob
-------
|->crond daemon
crontab -e {enter}
30 22 * * * /root/p1.sh
=============
/root/p1.sh {Enter}
Enter a IP Address:
--------------------------------------------------------------------
file: p2.sh
--------------
echo $1 $2 $3
---------------
root@host~]# chmod a+x p2.sh
root@host~]# ./p2.sh <input1> <input2> <input3> {Enter}
__________________________
|<= commandline args inputs
--------------
file: p1.sh
-------------
read -p "Enter a IP Address:" IP <== interactive input(or) execution input
read -p "Enter a count value:" count <== interactive input(or) execution input
-------------------------------------------
root@host~]# ./p1.sh {Enter} <==
Enter a IP Address: 127.0.0.1<== execution input
Vs
file: p3.sh
------------------------------------------
ping -c $1 $2 >/var/log/ping_test.log
-----------------------------------------
root@host~]# chmod a+x p3.sh
30 22 * * * /root/p3.sh 3 127.0.0.1
-----------
________________________________________________________________________________
if [ $# -eq 0 ];then
echo "Usage: Commandline args is empty"
fi
if [ $# -gt 3 ];then
echo "Usage: Given argument is more than 3"
fi
expr $1 + $2
-- --
[ -e <filename> ]
|
getting from <commandline>
$1 <== 1st argument
./p1.sh <inputfile>{Enter}
___________
if [ -e $1 ]
then
echo "file:$1 is exists"
else
echo "file:$1 is not exists"
fi
----------------------------------------------------------
Old version - shift command
-----
|->shift the positional parameters
shift <number>
--------
echo $1 $2 $3 $8 $9
-- -- -- -- ---
1st 2nd 3rd 8thposition 9thposition
shift 2
echo $1 $2 $3 $8 $9
-- -- -- -- ---
| | | | |->11th argument
| | | 10th argument
| | 5th argument
| 4th argument
3rd argument
------------------------------------------------------------------------------
Updated version -> ${n} - nth argument
$1 $2 $3... $9
(or)
${1} ${2} ${3} ... ${9} ${10} ${11} ... ${n}
mkdir $1
file: pt.sh
----------------
for v in $@
do
touch $v
done
------------------
./pt.sh test1 test2 test3 test4 {enter}
ls
test1 test2 test3 test4
-----------------------------------------------------------------------------------
-------------------