简单清理一下shell脚本接收参数的方式,估计只能适用sh、bash、zsh,其他shell不确定=。=
读取参数
# test.sh param1 param2
----------------
#!/bin/sh
# 第一个参数
$1
# 第n个参数(大于10的时候必须使用花括号)
${n}
脚本名
# 脚本名(包含调用路径)
$0
# 不包含路径的脚本名
${basename $0}
测试参数存在
if [ -n "$1" ]
then
echo Hello $1 .
else
echo Param1 not exist.
fi
参数统计
# 参数的总数(不包括脚本名)
$#
# 最后一个命令行的参数(因为花括号内不能用$,要替换成!)
${!#}
bash test10.sh 1 2 3 4 5
$ The last param is ${!#}
$ The last param is 5
抓取所参数(直接传递)
#!/bin/sh
echo "Using the \$* method: $*"
echo "Using the \$@ method: $@"
$ test.sh hello world foo bar
> Using the $* method: hello world foo bar
> Using the $@ method: hello world foo bar
# $* 会把所有参数当成一个字符串处理
# $@ 可以看作一个数组,可以遍历各个参数
for param in "$@"
do
echo $param
done
建议进一步增加文章的可读性与可重复性!
不是所有都是文章,很多都是片段=。=