例子:

~ script % touch 
~ script % chmod 755 
~ % vim 

:

#!/usr/bin/env bash

echo the name of current script is $0

echo the first parameter is $1

echo the second parameter is $2

echo all parameters: $@

exit 0

执行:

script % ./ a b
the name of current script is ./
the first parameter is a
the second parameter is b
all parameters: a b
  • $0 带全路径的脚本名称
  • $1 第1个参数
  • $2 第2个参数
  • $3 第3个参数
  • ${10} 第10个参数
  • ${255} 第255个参数
    最多可以有255个参数
  • $@: 获取所有参数,除了脚本名称,即$@等于$1~$255的参数的集合

我们可以通过查询$?了解脚本程序退出的状态。因为上面的脚本加了exit 0表示退出时的状态是0,一般来说,当程序出现异常导致退出时,状态值是个非0的整数。 如果我们加上这一句exit 10,执行完脚本后,再查询一个退出状态,就会得到10,查询的方式:

~ script % echo $?
10