shell_37.Linux参数传递和读取

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. 
$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微辣已是极限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值