Wednesday, October 3, 2012

Syntax for basic shell script constructs

  • if statement - can be used to perfroms a specific action/s based on the result of conditional expression
if [ a -eq b ]
then
.......
.......
else
........
........
fi
 
or
in one line
if [ a -eq b ]; then .......; .......; else ........; ........; fi
 
#Here ';' plays an important role. In unix ';' represents end of command line
 
ex:
$ if [ 1 = 2 ];then echo true;else echo false;fi
false
 
 
  • for statement - can be used to iterate through a list of values
 
array_list="1 2 3 4 5 6 7 8 9 10"
for i in $array_list
do
echo $i
done
 
in one line
array_list="1 2 3 4 5 6 7 8 9 10"; for i in $array_list; do echo $i; done
 
ex:
$ array_list="1 2 3 4 5 6 7 8 9 10"; for i in $array_list; do echo $i; done
1
2
3
4
5
6
7
8
9
10

  • while statement - can be used to read a list


any command that gives a list of values | while read a; do echo $a; done

$ ls t*|while read a; do echo $a; done
t
test
testif.ksh
tpt
try.ksh

  • To replace any search word on the fly in vi editor
to replace in whole file use Esc, then type :%s/findwors/replaceword/gc
This promts for confirmation every word it find and to replace

If you want to suppress promt remove c from the above command.

from a spefic line in file to specific line number
Esc then type :10,20s/findword/replaceword

No comments:

Post a Comment