最近由于工作需要,在学习ksh。几年前用过shell,但是现在看ksh脚本仍是一头雾水,感觉就是天书。在google上搜索了一把,教程倒是不少,但不是那种大而全的,就是那种太初级的入门小儿科,等于啥都没讲。为了方便查阅,在学习的同时,记录一些点滴。
if 语句
if [ $? -eq 0 ] ; then print we are okay else print something failed fi
$? - checks the exit status of the last command run.
case 语句
echo input yes or no read answer case $answer in yes|Yes|y) echo got a positive answer # the following ';;' is mandatory for every set # of comparative xxx) that you do ;; # ';;' is similar as break; in java case clause no) echo got a 'no' ;; q*|Q*) #assume the user wants to quit exit ;; *) echo This is the default clause. we are not sure why or echo what someone would be typing, but we could take echo action on it here ;; esac
关于case语句几点值得注意的地方
- 条件中的值可以是字符串和数字,不像java中只能是数字
- 如果希望某个case执行完后不再检查后面的case,可以使用;;,类似于java中的break。但是如果还是要继续后面的case检查,那就需要使用;&,类似于java中不要break.
- 可以在case中使用通配符,例如上面的例子中,如果answer的值以q或Q开头,则执行exit
while语句
keeplooping=1; while [[ $keeplooping -eq 1 ]] ; do read quitnow if [[ "$quitnow" = "yes" ]] ; then keeplooping=0 fi if [[ "$quitnow" = "q" ]] ; then break; fi done
几点解释
- read quitnow,是从console读取用户的输入并赋予变量quitnow
- [[ ... ]],类似于java中的括号(),[[ ... ]]里的字符一定要和[[和]]保持一个空格,否则shell会不认识
- break是跳出循环,这点和java中的语义是一样的
- if的结尾标识为fi,while的结尾标识为done
until语句
until [[ $stopnow -eq 1 ]] ; do echo just run this once stopnow=1; echo we should not be here again. done
for语句
for var in one two three ; do echo $var done
上面的例子是打印出one, two, three,和下面的例子同样的效果
list="one two three"
for var in $list ; do
echo $var
# Note: Changing this does NOT affect the loop items
list="nolist"
done
几点解释
- for var in $list和for var in "$list"是不一样的,前者会循环打印one, two, three,后者一次打印出one two three,因为#list会自动把"one two three"看成是一个string list,而"$list"则会把"one two three"整体看成是一个string
- 在for循环中,改变list的值并不会影响整个循环
括号的使用
two=2 print one$twothree print one${two}three
- one$twothree,这里会把$twothree看做是变量名,因此这一行会打印one,$twothree变量不存在,为空
- one${two}three,这里就知道$two是一个变量,因此打印one2three
- echo one{$two}three会打印one{2}three
数组
array[1]="one" array[2]="two" array[3]="three" three=3 echo ${array[1]} echo ${array[2]} echo ${array[3]} echo ${array[three]}
- 这里three被赋值3,因此array[3]和array[three]是一样的
- 可以用echo ${array[*]}一次性打印出array所有的元素
特殊变量
PWD - echo ${PWD} or echo $PWD always print the current directory
RANDOM - ${RANDOM} or $RANDOM, the different number every time you access it
$$ - echo $$ or ${$}, print the current process id of the script, NOT the user's shell
PPID - the "parent process" ID (but not always, for functions)
$? - echo $? or ${?}, the exit status of the last command run
$1 to $9 - arguments 1 to 9 passed to your script or function
${#var} - 表示变量var包含的character的字符个数
DATESTRING=${DATESTRING:-$(date)}
如果变量DATESTRING没有被赋值的话则给它赋值为date,否则跳过