csh脚本语法实例
csh实例 参考:
#!/bin/csh -vx
#csh -vx show the command before running to help debug
#just to check syntax
#csh -n $0
#argv
if ($#argv < 2) then
echo "sorry, but you entered too few parameters"
echo "usage: $0 arg1 arg2
exit
endif
set arg1 = $1
set arg2 = #2
foreach i ($*)
echo $i
end
#execute commands
echo "hello there `whoami`. how are you today?"
echo "you are currently using `hostname` and the time is `date`"
echo "your directory is `pwd`"
whoami
hostname
date
pwd
#var
set name = mark
echo $name
set name = "mark meyer" # if the string has space, must use ""
echo $name
# it means set to null
set name =
unset name
# get user input
set x = $<
set current_user = `whoami`
#buildin vars
echo $user # who am i?
echo $status # a numeric variable, usually used to retun error codes
#arithmetic variables
@ i = 2
@ k = ($x - 2) * 4
@ k = $k + 1
@ i--
@ i++
#array
set name = (mark sally kathy tony)
echo $#name # num of the array
echo $name[1]
echo $name[4]
echo $name[2-3]
echo $name[2-] # all elements from 2 to the end
echo $name[1-3]
echo $name[$i]
set name = ($name doran)
set name = (doran $name)
set name = ($name[1-2] alfie $name[3-])
shift name # get rid of the frist element of the array
shift #if no argument is given, it will get rid of argv
#expressions and operators
== equal (either strings or numbers)
!= not equal (either strings or numbers)
=~ string match
!~ string mismatch
<= numerical less than or equal to
>= numerical greater than or equal to
> numerical greater than
< numerical less than
-e file file merely exists (may be protected from user)
-r file file exists and is readable by user
-w file file is writable by user
-x file file is executable by user
-o file file is owned by user
-z file file has size 0
-f file file is an ordinary file
-d file file is a directory
! -- negate
&& -- logical and
|| -- logical or
#if-else
# run cmd as if expression
if ({grep -s junk $1}) then
echo "we found junk in file $1"
endif
# check if the var is defined
if ($?dirname) then
ls $dirname
endif
if (-e somefile) then
grep $1 somefile
else
echo "grievous error! database file does not exist".
endif
#foreach
foreach i (*)
if (-f $i) then
echo "============= $i ==================="
head $i
endif
if (-d $i) then
(cd $i; headers)
endif
end
#while
while ($#argv > 0)
grep $something $argv[1]
end
@ n = 5
while ($n)
# do something
@ n--
end
#switch-case
switch ($argv[$i])
case quit:
break # leave the switch statement
case list:
ls
breaksw
case delete:
case erase:
@ k = $i + 1
rm $argv[$k]
breaksw
endsw
#here document
grep $i <<here
john doe 101 surrey lane london, uk 5e7 j2k
angela langsbury 99 knightsbridge, apt. k4 liverpool
john major 10 downing street london
here
cat > tempdata <<endofdata
53.3 94.3 67.1
48.3 01.3 99.9
42.1 48.6 92.8
endofdata
exit 0