简体   繁体   中英

bash how to get async command output to variable

i want to know how can we get command output to variable in bash

here is my code

#!/bin/bash
opt="svcrack -v -u100 -r1-9999 -z3 10.0.0.1"
opt2="$($opt)"

echo "myout output $opt2"

output

myout output 

not working inside function :(

function zwork(){

opt=$(svcrack -v -u100 -r1-9999 -z3 10.0.0.1 2>&1)

echo "myout output $opt"
}

out=$(zwork)

Please try redirecting stderr to stdout like:

#!/bin/bash
opt=$(svcrack -v -u100 -r1-9999 -z3 10.0.0.1 2>&1)

echo "myout output $opt"

Here you can read more about command substition .

If you store a command in a variable in bash you need to use the eval keyword to execute that command. So in your case you should do something like this...

opt="svcrack -v -u100 -r1-9999 -z3 10.0.0.1"
opt2=$(eval $opt)
echo "myout output $opt2"

Correction : I was testing this in ZSH (not pure bash), so i needed to add the eval and ended up assuming that is the missing bit. However as someone corrected me in comment. That is not necessary.

Only problem in the OP script was

opt2="$($opt)"

it should have been

opt2=$($opt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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