1.传递参数
向 shell 脚本传递数据的最基本方法是使用命令行参数。命令行参数允许运行脚本时在命令行中添加数据:
$ ./addem 10 30
2.读取参数
(1)bash shell 会将所有的命令行参数都指派给称作位置参数(positional parameter)的特殊变量。
位置变量的名称都是标准数字:$0 对应脚本名,$1 对应第一个命令行参数,$2 对应第二个命令行参数,以此类推,直到$9。
例:
$ cat positional1.sh
#!/bin/bash
# Using one command-line parameter
#
factorial=1
for (( number = 1; number <= $1; number++ ))
do factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial
exit
$
$ ./positional1.sh 5
The factorial of 5 is 120
$
(2)如果需要输入更多的命令行参数,则参数之间必须用空格分开。
shell 会将其分配给对应的位置变量:
$ cat positional2.sh
#!/bin/bash
# Using two command-line parameters
#
product=$[ $1 * $2 ]
echo The first parameter is $1.
echo The second parameter is $2.
echo The product value is $product.
exit
$
$ ./positional2.sh 2 5
The first parameter is 2.
The second parameter is 5.
The product value is 10.
$
(3)也可以在命令行中用文本字符串作为参数:
$ cat stringparam.sh
#!/bin/bash
# Using one command-line string parameter
#
echo Hello $1, glad to meet you.
exit
$
$ ./stringparam.sh world
Hello world, glad to meet you.
$
(4)shell 将作为命令行参数的字符串值传给了脚本。但如果碰到含有空格的字符串,则会出现问题:
$ ./stringparam.sh big world
Hello big, glad to meet you.
$
(5)参数之间是以空格分隔的,所以 shell 会将字符串包含的空格视为两个参数的分隔符。
要想在参数值中加入空格,必须使用引号(单引号或双引号均可)。
$ ./stringparam.sh 'big world'
Hello big world, glad to meet you.
$
$ ./stringparam.sh "big world"
Hello big world, glad to meet you.
$
(6)如果脚本需要的命令行参数不止 9 个,则仍可以继续加入更多的参数,但是需要稍微修改一下位置变量名。
在第 9 个位置变量之后,必须在变量名两侧加上花括号,比如${10}
$ cat positional10.sh
#!/bin/bash
# Handling lots of command-line parameters
#
product=$[ ${10} * ${11} ]
echo The tenth parameter is ${10}.
echo The eleventh parameter is ${11}.
echo The product value is $product.
exit
$
$ ./positional10.sh 1 2 3 4 5 6 7 8 9 10 11 12
The tenth parameter is 10.
The eleventh parameter is 11.
The product value is 110.
$