处理用户输入_传递参数_读取参数
1. 使用单个命令行参数
#!/bin/bash
#bash shell会将所有的命令行参数都指派给称作位置参数(positional parameter)的特殊变量。
#位置变量的名称都是标准数字:$0 对应脚本名, $1 对应第一个命令行参数, $2 对应第2个命令行参数,直到$9
echo "************** 使用单个命令行参数 ***************"
# 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
# ./pass_parameter1.sh 5
运行结果:
2. 输入更多命令行参数
#!/bin/bash
# 如果需要输入更多命令行参数,参数之间用空格分开。
# using two command-line parameters
product=$[ $1 * $2 ]
echo the first parameter is $1
echo the second paramater is $2
echo the product value is $product
exit
# ./pass_parameter2.sh 2 5
运行结果:
3. 命令行中使用文本字符串作为参数
#!/bin/bash
# 也可以用在命令行中使用文本字符串作为参数
# using on command-line string parameter
echo hello $1, glad to meet you.
exit
# ./pass_parameter3.sh 'big world'
# ./pass_parameter3.sh "big world"
运行结果:
4. 脚本需要的命令行参数不止9个
#!/bin/bash
# 如果脚本需要的命令行参数不止9个,则在第9个位置变量之后,必须在变量名两侧加上花括号,比如${10}。
# handing lots of command-line parameter
product=$[ ${10} * ${11} ]
echo the tenth parameter is ${10}
echo the eleventh parameter is ${11}
echo the product value is $product
# ./pass_parameter4.sh 1 2 3 4 5 6 7 8 9 10 11 12
运行结果: