2

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. 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. 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; basically running the program without any options. And it creates tons of reports without the "-t createfin1report -1" part of the command (yikes!). 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 :)...

Thanks in advance!

6
  • 2
    Use an array for the command and arguments. Commented Oct 8, 2020 at 1:37
  • 1
    See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail! And avoid eval, it's a massive bug magnet. Commented Oct 8, 2020 at 1:42
  • BTW, cmd=$(somecommand) runs the command, and stores its output (not the command itself) in cmd -- is that what you intended here? Commented Oct 8, 2020 at 1:49
  • @GordonDavisson, yup you're right. that was a mistake I had. I want the command in the cmd variable, not the result. Commented Oct 8, 2020 at 3:49
  • One other question @GordonDavisson. If I were to store the entire command in an array like cmd=(auto_rep -t createfin1report -1), would I basically be able to run the command with just... ${cmd[@]} ? Thanks again! Commented Oct 8, 2020 at 4:01

1 Answer 1

2

Save output to an array, then executing this array.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.