简体   繁体   English

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

[英]How to pass shell variables as Command Line Argument to a shell script

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. 提前致谢。

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="${1}_${2}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 prodName and users before calling the script. 在这种情况下,您在调用脚本之前设置环境变量prodNameusers That is why you were able to use these variables inside your code. 这就是为什么你能够在代码中使用这些变量的原因。

#!/bin/sh    
prodName=$1
users=$2
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

Simple call it like this: sh script.sh DD 50 简单地称它为: sh script.sh DD 50

This script will read the command line arguments: 该脚本将读取命令行参数:

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

Here $1 will contain the first argument and $2 will contain the second argument. 这里$1将包含第一个参数, $2将包含第二个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM