bash 如何将 shell 变量作为命令行参数传递给 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27101736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:51:48  来源:igfitidea点击:

How to pass shell variables as Command Line Argument to a shell script

linuxbashshellcommandcommand-line-arguments

提问by user3627319

I have tried passing the shell variables to a shell script via command line arguments.

我尝试通过命令行参数将 shell 变量传递给 shell 脚本。

Below is the command written inside the shell script.

下面是写在 shell 脚本中的命令。

LOG_DIRECTORY="${prodName}_${users}users"
mkdir -m 777 "${LOG_DIRECTORY}"

and m trying to run this as:

我尝试将其运行为:

prodName='DD' users=50 ./StatCollection_DBServer.sh

The command is working fine and creating the directory as per my requirement. But the issue is I don't want to execute the shell script as mentioned below.

该命令工作正常并根据我的要求创建目录。但问题是我不想执行下面提到的 shell 脚本。

Instead, I want to run it like

相反,我想像这样运行它

DD 50 ./StatCollection_DBServer.sh

DD 50 ./StatCollection_DBServer.sh

And the script variables should get the value from here only and the Directory that will be created will be as "DD_50users".

并且脚本变量应该只从这里获取值,并且将创建的目录将作为“DD_50users”。

Any help on how to do this?

有关如何执行此操作的任何帮助?

Thanks in advance.

提前致谢。

回答by Thawn

Bash scripts take arguments after the call of the script not before so you need to call the script like this:

Bash 脚本在调用脚本之后而不是在调用之前接受参数,因此您需要像这样调用脚本:

./StatCollection_DBServer.sh DD 50

inside the script, you can access the variables as $1 and $2 so the script could look like this:

在脚本内部,您可以以 $1 和 $2 的形式访问变量,因此脚本可能如下所示:

#!/bin/bash
LOG_DIRECTORY="_users"
mkdir -m 777 "${LOG_DIRECTORY}"

I hope this helps...

我希望这有帮助...

Edit: Just a small explanation, what happened in your approach:

编辑:只是一个小小的解释,你的方法发生了什么:

prodName='DD' users=50 ./StatCollection_DBServer.sh

In this case, you set the environment variables prodNameand usersbefore calling the script. That is why you were able to use these variables inside your code.

在这种情况下,设置环境变量prodNameusers调用脚本之前。这就是您能够在代码中使用这些变量的原因。

回答by Hasan

#!/bin/sh    
prodName=
users=
LOG_DIRECTORY="${prodName}_${users}users"
echo $LOG_DIRECTORY
mkdir -m 777 "$LOG_DIRECTORY"

and call it like this :

并这样称呼它:

chmod +x script.sh
./script.sh DD 50

回答by BigBang

Simple call it like this: sh script.sh DD 50

简单地这样称呼它: sh script.sh DD 50

This script will read the command line arguments:

此脚本将读取命令行参数:

prodName=
users=
LOG_DIRECTORY="${prodName}_${users}users"
mkdir -m 777 "$LOG_DIRECTORY"

Here $1will contain the first argument and $2will contain the second argument.

这里$1将包含第一个参数,$2并将包含第二个参数。