How to store an output of shell script to a variable in Unix?
Solution 1:
Two simple examples to capture output the pwd
command:
$ b=$(pwd)
$ echo $b
/home/user1
or
$ a=`pwd`
$ echo $a
/home/user1
The first way is preferred. Note that there can't be any spaces after the =
for this to work.
Example using a short script:
#!/bin/bash
echo "hi there"
then:
$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there
In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.
Solution 2:
Suppose you want to store the result of an echo command
echo hello
x=$(echo hello)
echo "$x",world!
output:
hello
hello,world!
Solution 3:
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;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
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.
Solution 4:
export a=$(script.sh)
Hope this helps. Note there are no spaces between variable and =. To echo the output
echo $a