2

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)
5
  • 2
    I don't see anything asynchronous in your script. If that's the output you get, then your command just has no output on stdout. Commented Nov 12, 2015 at 6:34
  • it have output , svcrack is python script Commented Nov 12, 2015 at 6:37
  • I said no output on stdout. Judging from your "it worked" comment below, the output is on stderr, which doesn't contradict my diagnosis. But you should see output on stderr printed nevertheless if you're running the exact script as above in an interactive shell. Commented Nov 12, 2015 at 6:41
  • As an aside, variables are for data, not code. Either define a function named opt, or use the svcrack command directly in the command substitution as in the accepted answer. See I'm trying to put a command in a variable, but the complex cases always fail!. Commented Nov 12, 2015 at 12:11
  • Came late, but I guess you had to declare your function just as zwork(){ ... } instead of function zwork(){ ... } Commented Nov 7, 2022 at 19:47

2 Answers 2

1

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.

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

1 Comment

sir can u please check , its not working inside function , question update
0

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)

1 Comment

Not true. Parameter expansion goes before command substitution, so the original script is valid, albeit quite stupid.

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.