一、读取参数
$0 程序名称
$1 第一个参数
$2 第二个参数,依次类推
可以使用 basename 来读取程序名称:basename $0
在使用参数之前应该尽量测试参数 [ -n "$1" ] 由于需要将参数作为字符串因此添加引号
特殊的参数变量:
$# 表示参数个数, ${!#} 读取最后一个参数(由于不能在大括号中使用$符号,因此使用!代替)
$*
将所有参数作为一个对象
$@ 将所有参数使用空格分隔的多个对象(因此若一个参数包括空格,应该使用引号)
shift 移位,将$1->$0,
$2->$1 ......
while [ -n "$1" ] do case $1 in "-a") echo "Found the -a option";; "-b") echo "Found the -b option";; "-c") echo "Found the -c option";; "*") echo "$1 is not an option";; esac shift done count=1 cat test1.sh | while read line do echo "Line $count: $line" count=$[ $count+1 ] done
#使用read命令读取文件,cat test1.sh | while read line 表示将test1.sh依次读取,读取的行保存在line变量之中
二、输入输出
0 STDIN 标准输入 1 STDOUT 标准输出 2 STDERR 标准错误
command 2>err.log 1>nor.log #重定向标准错误与标准输出
echo "This is an error" >&2 #临时重定向到标准错误
exec 1>nor.log #永久重定向
exec 0<test1.sh count=1 while read line do echo "Line #$count: $line" count=$[$count+1] done #重定向标准输入的例子
可以创建自己的文件描述符:
exec 3>test.log echo "Test" >&3
重定向文件描述符:
exec 3>&1 exec 1>nor.log echo "This should store in the output file" echo "along with this line" exec 1>&3 echo "Now things should be back to normal"
exec 3>test.log
.....
exec 3>&- #关闭描述符
#在其中先保存3为标准输出,然后重定向标准输出到文件,完成输出后,在把标准输出恢复
列举文件描述符
/usr/sbin/lsof -p pid
禁止命令输出
ls -al > /dev/null
三、临时文件
mktemp zcs.XXXX #按照指定格式在本地目录创建临时文件 mktemp -t zcs.XXX #按照指定格式在系统临时目录创建临时文件 mktemp -d #用于创建临时目录
四、使用tee命令分流
date | tee tee.log
原文:http://www.cnblogs.com/chang290/p/3530169.html