1、命令行参数
向shell脚本传递数据的最基本方法是使用命令行参数。命令行参数允许在运行脚本时向命令行添加数据。
bash shell中有一种特殊的变量叫——位置参数,位置参数变量是标准的数字:$0是程序名,$1是第一个参数,$2是第二个参数,依次类推,直到第九个参数$9。
[root@relay3.mobvista.com:101.251.254.6 shell]#cat test.sh
#!/bin/bash
echo "The zero parameter is set to : $0"
[root@relay3.mobvista.com:101.251.254.6 shell]#sh test.sh
The zero parameter is set to : test.sh
但是这里存在一些问题,如果使用另一个命令来运行shell脚本,命令会和脚本名混在
一起,出现在$0参数中。或者说,当我们以绝对路径调用时,也会返回绝对路径。
[root@relay3.mobvista.com:101.251.254.6 shell]#./test.sh
The zero parameter is set to : ./test.sh
[root@relay3.mobvista.com:101.251.254.6 shell]#sh /root/shell/test.sh
The zero parameter is set to : /root/shell/test.sh
要编写一个根据脚本名来执行不同功能的脚本时,我们需要显示单纯的脚本名,而basename命令可以做到,它会返回不包含路径的脚本名。
[root@relay3.mobvista.com:101.251.254.6 shell]#cat test.sh
#!/bin/bash
name=$(basename $0)
echo "The zero parameter is set to : $name"
[root@relay3.mobvista.com:101.251.254.6 shell]#sh test.sh
The zero parameter is set to : test.sh
[root@relay3.mobvista.com:101.251.254.6 shell]#sh /root/shell/test.sh
The zero parameter is set to : test.sh
当脚本需要的命令行参数不止9个时,必须在变量数字周围加上花括号,比如${10}表示第十个参数。
[root@relay3.mobvista.com:101.251.254.6 shell]#cat test.sh
#!/bin/bash
total=$[ ${10} * ${11} ]
echo "The tenth is ${10}"
echo "The eleventh is ${11}"
echo "Th