views:

16

answers:

2

Hi, I would like to excute a command in shell script.

This command will have a return code, 0 or non-0 if success or not.

If success, it will print something.

Now I need the printed stuff in shell script. How can I do that?

I know that I might redirect to a file and then read the file. Is there any way to redirect it to a variable directly?

Thanks so much for your information.

+3  A: 

You can use the $(...) operator to capture a command's output as a string. You may have also seen the older backtick `...` syntax which does the same thing.

output=$(command)
output=`command`

echo "$output"

Command Substitution

Command substitution allows the output of a command to replace the command name. There are two forms:

$(command)

or

`command`

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.

If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

John Kugelman
+2  A: 
var=`command`

The backticks execute the command and return the result.

Michael Mior