将参数传递给脚本(Shell基础教程3)
将参数传递给脚本
在执行脚本时,可以通过命令行将参数传递给脚本。具体方法是在脚本文件名后跟随一个由空格分隔的参数列表。
在脚本内部,特殊变量用于引用这些参数:
$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)
- 变量 (Shell 基础教程 2)
- 将参数传递给脚本 (Shell 基础教程 3)
- 数组 (Shell 基础教程 4)
- 数组比较 (Shell 基础教程 5)
- 基本运算符 (Shell 基础教程 6)
- 基本字符串操作 (Shell 基础教程 7)
- 逻辑表达式 (Shell 基础教程 8)
- 循环 (Shell 基础教程 9)
- shell 函数 (Shell 基础教程 10)
- 特殊变量 (Shell 基础教程 11)
- 字符串操作 (Shell 基础教程 12)
- 捕捉信号命令 (Shell 基础教程 13)
- 文件测试 (Shell 基础教程 14)
- 输入参数解析 (Shell 基础教程 15)
- 管道 (Shell 基础教程 16)
- 输入输出 (Shell 基础教程 17)
- 常用表达 (Shell 基础教程 18)
- 特殊命令 sed(Shell 基础教程 19)
版权声明:本文为原创文章,版权归 戴老师的博客 所有,转载请联系博主获得授权。
本文地址:https://1diff.fun/archives/jiang-can-shu-chuan-di-gei-jiao-ben-shell-ji-chu-jiao-cheng-3.html
如果对本文有什么问题或疑问都可以在评论区留言,我看到后会尽量解答。