如何在Java中通过bash传递类似于$(date +"%Y")的命令参数?

huangapple go评论78阅读模式
英文:

How to pass an command argument like $(date +"%Y") in bash through java?

问题

我知道我们可以通过Java中的Runtime在bash中传递参数。我有一个特殊情况,我想像这样传递参数:$(date +"%Y""%m"),作为bash中的一个参数,然后在bash中计算并存储在一个变量中。考虑以下Java代码:

String[] cmd = {"/bin/bash", "/user/username/test.sh", "firstparameter", "date +%Y", "folder_$(date +%Y)"};
Process process = Runtime.getRuntime().exec(cmd);


上述命令运行了shell脚本test.sh。我的脚本内容如下:

first=$1
year=$2
foldername=$3

echo $first
echo $year
echo $foldername


我在bash代码中使用了反引号,这样通过Java程序传递的参数就可以先执行。命令的输出将会是:

firstparameter
2020
$(date: not found


我希望bash中的foldername变量是folder_2020。我们如何实现这个目标?我尝试了很多次,但没有成功。非常感谢任何帮助。
英文:

I know we can pass argument in bash through the Runtime in java. I have a special case, I want to pass arguments like $(date +"%Y""%m") as a parameter in the bash which will in turn be computed and stored in a variable in bash. Consider the following java code:

String[] cmd = {"/bin/bash", "/user/username/test.sh", "firstparameter", "date +%Y", "folder_$(date +%Y)";
Process process = Runtime.getRuntime().exec(cmd);

The above command runs the shell script test.sh. My script goes as follows:

first=$1
year=`$2`
foldername=`$3`

echo $first
echo $year
echo $foldername

I have included backticks on my bash code so that the argument passed through the java program can be executed first. The output of the command will be:

firstparameter
2020
$(date: not found

I want the bash to have the foldername as folder_2020. How can we achieve this? I tried many times but could not succeed. Any help will be highly appreciated.

答案1

得分: 2

你可以替换最后一个参数:

"folder_$(date +%Y)"

"date +folder_%Y"

将参数转换为有效命令可以确保在Shell脚本中按预期执行。


或者,您可以保留最后一个参数不变,而是修改您的Shell脚本。

将这个变量赋值:

foldername=`$3`

替换为这个:

eval "foldername=\"\$3\""

eval调用将处理嵌入在$3中的任何命令替换。

英文:

You can replace the last argument:

"folder_$(date +%Y)"

with

"date +folder_%Y"

Making the argument into a valid command ensuress that it will execute as intended in the shell script.


Alternatively you can leave your last argument as is, and modify your shell script instead.

Replace this variable assignment:

foldername=`$3`

with this:

eval "foldername=\"$3\""

The eval call will take care of performing any command substitution that is embedded in $3.

huangapple
  • 本文由 发表于 2020年4月10日 09:41:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61132825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定