T4 Shell Programming
T4 Shell Programming
Oleh:
Idris Winarno
My first Shell Script
• vi myfirstscript.sh
#! /bin/csh
set directory=`pwd`
echo The date today is `date`
echo The current directory is $directory
• vi myinputs.sh
#! /bin/csh
echo Total number of inputs: $#argv
echo First input: $argv[1]
echo Second input: $argv[2]
• vi math.sh
#!/bin/csh
set count=5
set count=`expr $count + 1`
echo $count
• chmod u+x math.sh
• math.sh
Shell Programming
• if-then
if ( expr ) simple-command
• if-then-else
if ( expr ) then
command-set-1
[else
command-set-2]
endif
Decision Logic (cont’d)
• Contoh
#!/bin/csh
if ($#argv != 2) then
echo $0 needs two parameters!
echo You are inputting $#argv parameters.
else
set par1 = $argv[1]
set par2 = $argv[2]
endif
Decision Logic (cont’d)
Contoh:
#! /bin/csh
# number is positive, zero or negative
echo "enter a number:"
set number = $<
if ( $number < 0 ) then
echo "negative"
else if ( $number == 0 ) then
echo zero
else
echo positive
endif
Decision Logic (cont’d)
Contoh:
#!/bin/csh
if {( grep UNIX $argv[1] > /dev/null )} then
echo UNIX occurs in $argv[1]
else
echo No!
echo UNIX does not occur in $argv[1]
endif
Looping Logic
while ( expr )
command_set
end
Program:
#!/bin/csh
foreach person (Bob Susan Joe Gerry)
echo Hello $person
end
Output:
Hello Bob
Hello Susan
Hello Joe
Hello Gerry
Looping Logic
switch ( var )
case string1:
command_set_1
breaksw
case string2:
command_set_2
breaksw
default
command_set_3
endsw
Switch Logic
#!/bin/csh
if ($#argv == 0 ) then
echo "No arguments supplied...exiting"
else
switch ($argv[1])
case [yY]:
echo Argument one is yes.
breaksw
case [nN]:
echo Argument one is no.
breaksw
default:
echo Argument one is neither yes nor no.
breaksw
endsw
endif
Kesimpulan