侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 742 篇文章
  • 累计创建 64 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Shell脚本编程(7)之命令行参数

zze
zze
2019-12-23 / 0 评论 / 0 点赞 / 598 阅读 / 2755 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

本部分内容参考自《Linux命令行与shell脚本编程大全 第3版》。

向 shell 脚本传递数据的最基本方法是使用命令行参数。命令行参数允许在运行脚本时向命令行添加数据。

$ ./addem 10 30

本例向脚本 addem 传递了两个命令行参数( 10 和 30)。脚本会通过特殊的变量来处理命令行参数。

读取参数

bash shell 会将一些称为位置参数( positional parameter)的特殊变量分配给输入到命令行中的所有参数。这也包括 shell 所执行的脚本名称。位置参数变量是标准的数字:$0 是程序名,$1 是第一个参数, $2 是第二个参数,依次类推,直到第九个参数$9
下面是在 shell 脚本中使用单个命令行参数的简单例子。

$ cat test11.sh 
#!/bin/bash
factorial=1
for (( number = 1; number <= $1 ; number++ ))
do
	factorial=$[ $factorial * $number ]
done
echo The factorial of $1 is $factorial
$ ./test11.sh 5
The factorial of 5 is 120

可以在 shell 脚本中像使用其他变量一样使用 $1 变量。 shell 脚本会自动将命令行参数的值分配给变量,不需要你作任何处理。
如果需要输入更多的命令行参数,则每个参数都必须用空格分开。

$ cat test12.sh 
#!/bin/bash
total=$[ $1 * $2 ]
echo The first parameter is $1.
echo The second parameter is $2.
echo The total value is $total.
$ ./test12.sh 2 3
The first parameter is 2.
The second parameter is 3.
The total value is 6.

shell 会将每个参数分配给对应的变量。
在前面的例子中,用到的命令行参数都是数值。也可以在命令行上用文本字符串。

$ cat test13.sh 
#!/bin/bash
echo "Hello $1"
$ ./test13.sh zhangsan
Hello zhangsan

如果脚本需要的命令行参数不止 9 个,你仍然可以处理,但是需要稍微修改一下变量名。在第 9 个变量之后,你必须在变量数字周围加上花括号,比如 ${10}。下面是一个这样的例子。

$ cat test14.sh 
#!/bin/bash
total=$[ ${10} * ${11} ]
echo The tenth parameter is ${10}
echo The eleventh parameter is ${11}
echo The total is $total
$ ./test14.sh 1 2 3 4 5 6 7 8 9 10 11 12
The tenth parameter is 10
The eleventh parameter is 11
The total is 110

这项技术允许你根据需要向脚本添加任意多的命令行参数。

读取脚本名

可以用 $0 参数获取 shell 在命令行启动的脚本名。这在编写多功能工具时很方便。

$ cat test15.sh 
#!/bin/bash
echo The zero parameter is set to: $0
$ ./test15.sh 
The zero parameter is set to: ./test15.sh

但是这里存在一个潜在的问题。命令会和脚本名混在一起,出现在 $0 参数中。
这还不是唯一的问题。当传给 $0 变量的实际字符串不仅仅是脚本名,而是完整的脚本路径时,变量 $0 就会使用整个路径。

$ /root/scripts/1223/test15.sh 
The zero parameter is set to: /root/scripts/1223/test15.sh

如果你要编写一个根据脚本名来执行不同功能的脚本,就得做点额外工作。你得把脚本的运行路径给剥离掉。另外,还要删除与脚本名混杂在一起的命令。
幸好有个方便的小命令可以帮到我们。 basename 命令会返回不包含路径的脚本名。

$ cat test16.sh 
#!/bin/bash
name=$(basename $0)
echo The script name is: $name
$ /root/scripts/1223/test16.sh 
The script name is: test16.sh

这样就好多了。

0

评论区