[shell] How to store an output of shell script to a variable in Unix?

i have a shell script "script.sh" which gives output as "success" or "Failed" when i execute in unix window. Now i want to store the output of script.sh into a unix command variable. say $a = {output of script.sh}

This question is related to shell unix

The answer is

Suppose you want to store the result of an echo command

echo hello   
x=$(echo hello)  
echo "$x",world!  



You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
    echo script failed

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

export a=$(script.sh)

Hope this helps. Note there are no spaces between variable and =. To echo the output

echo $a