一、使用命令行参数
参数$1,$2,$3,$4(直到$9)分别对应第1个、第2个、第3个、第4个命令行参数,参数$0是Shell程序自身。
$#表示传递到脚本的参数的个数
$*表示所有的命令行参数
位置参数位移
#!/bin/sh
# quickmail - send mail from the command line
# useage:quickmail recipient subject contents
RECIPIENT=$1
SUBJECT=$2
shift;shift
(echo $*) | mail $RECIPIENT -s $SUBJECT
echo $# word message sent to $RECIPIENT.
现将前两个参数保存到变量RECIPIENT和SUBJECT中,然后用两个shift命令将位置参数表移动两次,shift命令执行后,$1变为原命令行的第3个参数。
set命令
set *
echo "There are $# files in the current directory."
Shell的set命令用于将字符串中每一个单词依次赋值给位置参数。
二、算术运算
expr命令的缺陷
expr命令的语法与Shell自身的语法有冲突,所以expr命令比较难以使用。expr命令可以使用"+","-","*",和"/"运算,但是*前必须加反斜线,以防止Shell将它解释维星号。
$ expr 5 + 6
$ expr 4 \* 4
同时expr命令只能够用于整数算术运算,若是参数之间没有加空格,expr命令就不解释执行表达式。
使用let命令进行算术运算
在ksh和bash中,let命令可以替代expr,它提供更简单,更完善的方法来进行整数算术运算。
$ x=100
$ let y=2*(x+5)
$ echo $y
210
ps:let命令自动使用变量(如x或y)的值,不用在变量名前加$
let x=x+3等价 ((x = x+3))
三、条件执行
if testcommand
then
command(s)
fi
逻辑判断条件
test命令可以比较整数或字符串,test -eq 用于判断两个整数是否相等
eg:
if test $# -eq 0
then
echo "No command line arguments provided,setting user to current user."
username=$LOGNAME
fi
如果$#等于0,就系那是一条信息并设置变量username.
表一 整数判断
整数判断 为真的条件
n1 -eq n2 n1等于n2
n1 -ne n2 n1不等于n2
n1 -gt n2 n1大于n2
n1 -ge n2 n1大于或等于n2
n1 -lt n2 n1小于n2
n1 -le n2 n1小于或等于n2
表二 字符串判断
-z string string的长度为0
-n string string的长度不为0
string string非空(如同-n)
string1=string2 string1 与string2相同
string1!=string2 string1 与 string2不相同
表三 逻辑操作符
操作符 说明
! 非
-a 与
-o 或
方括号判断
方括号与文字之间必须使用空格分隔
if [ $# -eq 0 ]
在 ksh 和 bash中判断
ksh和bash提供“[[]]”运算符,也可以用于替代test命令。
[[ ! ( $x > 0 && $y > 0 ) ]]
若是用test命令,必须如下所示输入:
test ! \( $x -gt 0 -a $y -gt 0 \)
文件和目录的判断
文件判断和目录判断
文件/目录判断 为真的条件
-a file file存在
-r file file存在并且可读
-w file file存在并且可写
-x file file存在并且可执行
-f file file存在并且是常规文件
-d file file存在并且是目录
-h file file存在并且是符号链接
-c file file存在并且是字符专用文件
退出脚本
if [ ! -a "$1" ]
then
echo "File $1 not found."
exit 2
fi
if..elif..else
if testcommand
then
commands(s)
elif testcommand
then
case语句
case string
in
pattern)
command(s)
;;
pattern)
command(s)
;;
esac
commands(s)
else
command(s)
fi
简摘自:《UNIX完全手册(第二版)》 Kenneth Rosen , James Farber,Douglas Host,Rachel Klee,Richard Rosinski著 刑国庆,黄辰,刘琦 译
5
Posted by 222.247.54.10 on November 04, 2009 at 01:39 PM CST #