简体   繁体   English

Bash脚本:将带空格的命令和arguments存储在变量中,然后执行

[英]Bash script : Storing command with spaces and arguments in variable and then executing

Been banging my head against the wall for a couple hours so time to call in the experts.几个小时以来我一直在用头撞墙,所以有时间请专家来。 Writing a small script to run some reports on one of my office's systems and I was asked to take care of a Bash script for it.编写一个小脚本来在我办公室的一个系统上运行一些报告,我被要求为它处理一个 Bash 脚本。 The program called "auto_rep" takes various options such as "-t" to run one task (to generate one type of report) and a "-1" to exit after one task.名为“auto_rep”的程序采用各种选项,例如“-t”运行一项任务(生成一种类型的报告)和“-1”在完成一项任务后退出。 The options are separated by spaces when running the command from command-line.从命令行运行命令时,选项以空格分隔。 The command works directly from command line but I cannot get it to work from a script...该命令直接从命令行运行,但我无法从脚本运行...

Below is the snippet of code causing me issues:以下是导致我出现问题的代码片段:

cmd=$(auto_rep -t createfin1report -1)
echo "running ${cmd} command..."
echo
eval $cmd

The problem is when I run the script, only the "auto_rep" part of the command (from $cmd variable) is run;问题是当我运行脚本时,只运行命令的“auto_rep”部分(来自 $cmd 变量); basically running the program without any options.基本上在没有任何选项的情况下运行程序。 And it creates tons of reports without the "-t createfin1report -1" part of the command (yikes.).它会在没有命令的“-t createfin1report -1”部分的情况下创建大量报告(哎呀。)。 Glad I only tried it on our test system.很高兴我只在我们的测试系统上尝试过。

Anyone have any tips to help me out?任何人有任何提示可以帮助我吗? Is my approach way off?我的方法偏离了吗? BTW - had tried just storing the command in a non-array (cmd="auto_rep -t createfin1report -1") and that was causing me other headache with a "command not found" errors:)...顺便说一句 - 曾尝试将命令存储在非数组中(cmd =“auto_rep -t createfin1report -1”),这让我头疼“找不到命令”错误:)......

Thanks in advance!提前致谢!

Save output to an array, then executing this array.将output保存到一个数组中,然后执行这个数组。

declare -a cmd
cmd=( $(auto_rep -t createfin1report -1) )
echo Executing: "${cmd[@]}"
"${cmd[@]}"

Please make sure the output is a valid command, and spaces have been correctly placed in double-quotes.请确保 output 是一个有效的命令,并且空格已正确放置在双引号中。

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

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