0%

Shell传参

参数

无论什么时候运行 shell 脚本,shell 会自动把参数保存到 12 等变量中,后续使用 $1$2 来引用。

这些特殊的变量通常叫做 positional parameters,因为这边变量是和位置相关的,在 shell 完成正常的处理(I/O redirection、variable substitution、filename substitution)后被分配。

$#

$# 保存了传递的变量的个数。

1
2
3
# args
echo $1 arguments passed
echo arg 1 = :$1: arg 2 = :$2: arg 3 = :$3:
1
2
3
4
5
$ args a b c
$ args a b
$ args "a b c"
$ args x* # 以 x 开头的文件
$ args $my_bin

$*

$* 保存了所有传递的参数。

1
2
3
# args2
echo $# args passed
echo they are :$*:
1
2
3
4
$ args2 a b c
$ args2 one two
2 args passed
they are :one two:

demo

A Programe to look up someone in the phone book

1
2
3
4
5
#
# look up someone in the phone book
#
# grep $1 phonebook
grep "$1" phonebook

A Programe to add someone in the phone book

1
2
3
4
5
# add
echo "$1 $2" >> phonebook
sort -o phonebook phonebook

# add "John Smith" 871-221-4867

A Programe to remove someone in the phone book

1
2
3
# rem
grep -v "$1" phonebook > /tmp/phonebook # 可能会删除多个
mv /tmp/phonebook phonebook

${n}

当使用超过 9 个参数时,怎么引用第 10 个参数呢?$10 会被解析为第一个参数后加个 0,解决方法是 ${10}

shift

shift 允许左移位置参数,使用 shift 会把原来保存在 $2 的参数放到 $1 中,$3 –> $2,以此类推,而原来的 $1 消失了。

执行此命令时 $# 也会减1。

1
2
3
4
5
6
7
8
9
10
11
12
# tshift
echo $# $*
shift
echo $# $*
shift
echo $# $*
shift
echo $# $*
shift
echo $# $*
shift
echo $# $*
1
2
3
4
5
6
7
./tshift a b c d e
5 a b c d e
4 b c d e
3 c d e
2 d e
1 e
0

也可以一次移动多个,shift 3 就相当于使用了三次 shift