1

In Bash I need to run a variable containing commands, and then assign the output to another variable. The problem is there are several commands and there are some pipes or something like that.

Below is a sample:

snmpwalk -Ov -v 2c -c public 127.0.0.1 1.3.6.1.4.1.6574.1.2.0 | awk "{print $2}"

And:

upsc ups | grep input.voltage: | cut -d" " -f2

How can I do this?

4
  • 6
    Use eval. But be wary that eval is evil when string is not sanitized. Ever heard of Exploits of a Mom? Commented Apr 22, 2016 at 22:59
  • 1
    The jokers in your woodpile are the awk program and the -d" " argument to cut, because they contain spaces which make plain string handling into a complete pain. In principle, eval "${array[@]}" will then 'work', but you have to be so careful it is unbearable (which is why this isn't an answer). Using array=(snmpwalk -Ov -v 2c -c public 127.0.0.1 1.3.6.1.4.1.6574.1.2.0 '|' awk "'{print \$2}'") allows you to use eval "${array[$@]}", but note the double quotes around single quotes and the escaped dollar; they don't lend themselves to easy handling. […continued…] Commented Apr 23, 2016 at 1:34
  • […continuation…] Often, your best bet is to get the content into a file and then execute the file. At least that is readily debuggable. Commented Apr 23, 2016 at 1:35
  • Yes, I've got the idea to write the variable content into file and execute it right after make this post. Did not try it yet. It doesn't look like pure solution but should do the work... Thank you. Commented Apr 23, 2016 at 3:03

2 Answers 2

1

Here's a way:

cmd='upsc ups | grep input.voltage: | cut -d" " -f2'
result=`echo "$cmd" | bash`
Sign up to request clarification or add additional context in comments.

Comments

0

You can capture the stdout of any command or pipeline to a variable like this:

result=$(upsc ups | grep input.voltage: | cut -d" " -f2)

1 Comment

I think you've missed what the question is asking about.

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.