Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

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}

like image 504
logan Avatar asked Jun 08 '12 11:06

logan


People also ask

How do you store shell variables?

Shell variables are stored in the memory of the running shell. Use any data structure that lets you easily look up an item given its name; a hash table is a good choice. The difference between shell variables and environment variables is that environment variables are placed in the environment of subprocesses.


1 Answers

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.

like image 168
Levon Avatar answered Sep 23 '22 06:09

Levon