将参数传递给脚本(Shell基础教程3.html)
将参数传递给脚本
在执行脚本时,可以通过命令行将参数传递给脚本。具体方法是在脚本文件名后跟随一个由空格分隔的参数列表。
在脚本内部,特殊变量用于引用这些参数:
$1变量引用命令行中的第一个参数。$2变量引用第二个参数,依此类推。$0变量引用当前脚本的名称。
以下示例展示了脚本名称后跟随 6 个参数的情况:
./bin/my_shopping.sh apple 5 banana 8 "Fruit Basket" 15在脚本内部,可以通过以下方式访问这些参数:
echo $3 # 输出结果:banana
BIG=$5
echo "A $BIG costs just $6" # 输出结果:A Fruit Basket costs just 15特殊变量
除了位置参数外,Shell 还提供了一些特殊变量来处理参数列表:
参数数量:变量
$#存储传递给脚本的参数数量。echo $# # 输出结果:6- 所有参数:变量
$@包含传递给脚本的所有参数列表。
练习说明
本节没有练习。您可以继续学习后续内容。
教程代码
#!/bin/bash
# There is no exercise for this section.
# You may proceed.解决方案
#!/bin/bash
# There is no exercise for this section.
# You may proceed.预期输出
#!/bin/bash
# There is no exercise for this section.
# You may proceed.系列教程导航
- Hello, World!(Shell 基础教程 1.html)
- 变量 (Shell 基础教程 2.html)
- 将参数传递给脚本 (Shell 基础教程 3.html)
- 数组 (Shell 基础教程 4.html)
- 数组比较 (Shell 基础教程 5.html)
- 基本运算符 (Shell 基础教程 6.html)
- 基本字符串操作 (Shell 基础教程 7.html)
- 逻辑表达式 (Shell 基础教程 8.html)
- 循环 (Shell 基础教程 9.html)
- shell 函数 (Shell 基础教程 10.html)
- 特殊变量 (Shell 基础教程 11.html)
- 字符串操作 (Shell 基础教程 12.html)
- 捕捉信号命令 (Shell 基础教程 13.html)
- 文件测试 (Shell 基础教程 14.html)
- 输入参数解析 (Shell 基础教程 15.html)
- 管道 (Shell 基础教程 16.html)
- 输入输出 (Shell 基础教程 17.html)
- 常用表达 (Shell 基础教程 18.html)
- 特殊命令 sed(Shell 基础教程 19.html)
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://www.tushu.info/archives/jiang-can-shu-chuan-di-gei-jiao-ben-shell-ji-chu-jiao-cheng-3.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。