Shell脚本学习笔记---基本参数解析
常见命令行参数意义
菜鸟们总会被shell脚本中常见变量弄混淆,这些变量有$?, $#, $0, $@, $*
$?表示前一个命令的返回值,0表示正确,非0值表示错误
#test05.sh
#!/bin/bash
sh test01.sh
if [ $? -ne 0 ]; then
echo "test01.sh excute failed!"
else
echo "test01.sh excute right!"
fi
#test01.sh
#!/bin/bash
array=(zl love ll forever)
for((i=0;i<${#array[@]};i++)); do
printf "%s " ${array[$i]}
done
printf "\n"
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test05.sh
zl love ll forever
test01.sh excute right!
$#表示命令行参数个数,相当于C语言中的argc
$0表示本脚本的名称
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ vim test03.sh
#!/bin/bash
echo $0
结果如下
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test03.sh
test03.sh
所以$0参数还是很有用的,尤其在目录结构上,例如:
#!/bin/bash
cd `dirname $0`
source ../conf.sh
$@和$*都表示命令行参数,二者存在细微的区别:
共同之处:
echo "begin:"
for i in $@
do
echo $i
done;
result:
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test05.sh zl love ll 1314
begin:
zl
love
ll
1314
echo "begin:"
for i in $*
do
echo $i
done;
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test05.sh zl love ll 1314
begin:
zl
love
ll
1314
不同之处:
for i in "$@"
do
echo $i
done;
result:
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test05.sh zl love ll 1314
begin:
zl
love
ll
1314
echo "begin:"
for i in "$*"
do
echo $i
done;
[work@yx-dpfqa-a111.yx01.baidu.com shell]$ sh test05.sh zl love ll 1314
begin:
zl love ll 1314