在shell脚本中常常用到一些特殊参数,如$0、$1等。那么这些参数如何使用:
$0 表示脚本文件的名称,如:编写一个文件名为variable.sh的脚本
#!/bin/bash
echo “the name of this script is $0”
exit
执行脚本标准输出为variable.sh脚本文件名字
$1表示传递给脚本的第一个参数,$2传递给脚本的第二个参数,$3表示传递给脚本的第三个参数,以此类推$4,$5…. 但是参数超过10个则需要用{}括起来,例如:
#!/bin/bash
if [ -n $1 ]
then
echo “the first paramter is $1.”
fi
if [ -n $2 ]
then
echo “the second parmeter is $2.”
fi
if [ -n $3 ]
then
echo “the second parmeter is $3.”
fi
exit 0
执行脚本 sh variable.sh 1 2 3 输出结果为 the first paramter is 1 . the second parmeter is 2. “the second parmeter is 3.
$* 用于匹配所有传递进来的的参数;
$# 添加到shell的参数个数;
$- 使用set命令设定的Flag一览;
$? 最后运行的命令的返回值;
$! shell最后运行的process的pid;
$$ shell本身的pid;
然而在执行脚本程序时未输入任何参数,那么在调用时就会导致出现空变量进而引起其他问题。要解决这样的问题,我们可以在这个位置参数及相关变量后都添加一个额外的字符,这样shell在读取不到参数时,默认调用额外添加的字符。例如:
#!/bin/bash
a_=$1_
b=$a_
echo $b
exit 0
执行脚本输出如果不提供参数输出_
差点忘了还有一个$@这个跟$*差不多 $*所有参数都在一个双引号里,$@每个参数都是一个独立的双引号引用的字符串。