Fred
Fred

Reputation: 419

bash : parse output of command and store into variable

I have made a command witch return 'version:X' .

ie:

$>./mybox -v
$>version:2

I don't understand why this isn't working :

 $>VERSION=$( /home/mybox -v | sed 's/.*version:\([0-9]*\).*/\1/')
 $>echo $VERSION
 $>

if I write this, it is ok :

 $>VERSION=$( echo "version:2" | sed 's/.*version:\([0-9]*\).*/\1/')
 $>echo $VERSION
 $>2

Regards

Upvotes: 0

Views: 715

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95614

It's pretty common for version/error/debugging information to be sent to stderr, not stdout. When running the command from a terminal, both will be printed, but only stdout will make it through the pipe to sed.

echo output always goes to stdout by default, which is why you're not having trouble there.

If the above is correct, you'll just need to redirect stderr (file descriptor 2) to stdout (file descriptor 1) before passing it along:

VERSION=$( /home/mybox -v 2>&1 | sed 's/.*version:\([0-9]*\).*/\1/')
#                         ^^^^

Upvotes: 5

Related Questions