1、位置变量
也称系统变量或位置参数,是shell脚本运行时,传递给脚本的参数
名称以数字命名,如:$1, $2, ${10}
测试程序如下:
#!/bin/bash
#test.sh
#test var
#by wzs 2017/10/23
echo "the number of parameters is $#"
echo "the return code of last command is $?"
echo "the script name is $0"
echo "the parameters is $*"
echo "\$1 = $1; \$2 = $2"
运行结果如下:
book@wzs:~/work/tq210/shell$ ./test.sh aa bb
the number of parameters is 2
the return code of last command is 0
the script name is ./test.sh
the parameters is aa bb
$1 = aa; $2 = bb
脚本中判断前一个命令的返回值,一般成功返回0,失败返回非0,如下:
#!/bin/bash
#test.sh
#test var
#by wzs 2017/10/23
if [ $# -ne 2 ];
then
echo "Usage:$0 string files";
exit 1;
fi
grep $1 $2 -nR;
if [ $? -ne 0 ];
then
echo "Not found \"$1\" in $2";
exit 1;
fi
echo "Found \"$1\" in $2";
执行方式一:
book@wzs:~/work/tq210/shell$ ./test.sh xxx bb.txt
Not found "xxx" in bb.txt
由于在bb.txt文件里没有匹配到"xxx"所以,grep命令返回非0
执行方式二:
book@wzs:~/work/tq210/shell$ ./test.sh a bb.txt
1:fda
2:afda
Found "a" in bb.txt
匹配到字符"a",所以grep命令返回值是0