Bash参数


文档摘要

Bash 参数 在执行 Shell 脚本时,您可以向脚本传递参数。要传递参数,只需在脚本名称后直接写上参数即可。例如: 在脚本中,我们可以使用 in order to reference the first argument that we specified. If we pass a second argument, it would be available as and so on. Let's create a short script called 作为示例: 保存文件并使其可执行: 然后运行该文件并传递 3 个参数: 您将得到以下输出: 要引用所有参数,可以使用 : 如果您再次运行该脚本: 您将得到以下输出: 另外需要注意的一点是, 用于引用脚本本身。

Bash 参数

在执行 Shell 脚本时,您可以向脚本传递参数。要传递参数,只需在脚本名称后直接写上参数即可。例如:

./devdojo.com your_argument

在脚本中,我们可以使用 $1 in order to reference the first argument that we specified.

If we pass a second argument, it would be available as $2 and so on.

Let's create a short script called arguments.sh 作为示例:

#!/bin/bash echo "Argument one is $1" echo "Argument two is $2" echo "Argument three is $3"

保存文件并使其可执行:

chmod +x arguments.sh

然后运行该文件并传递 3 个参数:

./arguments.sh dog cat bird

您将得到以下输出:

Argument one is dog Argument two is cat Argument three is bird

要引用所有参数,可以使用 $@

#!/bin/bash echo "All arguments: $@"

如果您再次运行该脚本:

./arguments.sh dog cat bird

您将得到以下输出:

All arguments: dog cat bird

另外需要注意的一点是,$0 用于引用脚本本身。

如果需要,这是一种创建自毁脚本的绝佳方式,或者只是获取脚本名称的一种方法。

例如,让我们创建一个脚本,该脚本会打印出文件名并在之后删除该文件:

#!/bin/bash echo "The name of the file is: $0 and it is going to be self-deleted." rm -f $0

在进行自删除操作时需要格外小心,并确保在自删除之前已备份好脚本。

免责声明
本文件由基于人工智能的机器翻译服务翻译而成。尽管我们力求翻译准确,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言版本的文件为准。对于关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。


发布者: 作者: 转发
评论区 (0)
U