This is fairly easy to do compared to the amount of trouble i had to go through to find it. All you have to do is to surround the shell command with the “`” character (this is not the single quote character) and assign the whole string to the variable name.
eg:
$ n=`ls`
$ echo $n
pom.xml src target
Its as simple as that. Have fun.
Tags: linux command save to variable, save command output to variable, save output of a linux command to a bash sh variable
March 19, 2009 at 1:07 pm |
thanq….
June 3, 2009 at 10:23 am |
Hi,
I tried this one
$ cre=`mkdir -p 1/2/3`
—expecting that cre is holding the directory 1/2/3
$ cd 1/2/3
$ touch file1
$ cd
$ echo “hello” >> $cre/file
—since “cre” is directory 1/2/3
but when i vim file1, i didn’t saw the word hello there.
What wrong with what I’ve done?
June 3, 2009 at 11:01 am |
Hi jay,
mkdir command does not return any texual information if the operation is successful. Thus the variable “cre” will contain an empty string. Therefore it does not return the directory structure it created when the command is executed. If an error occurred then that texual information will be assigned to the variable “cre”.
What you can do is.
$ cre=”1/2/3″
$ mkdir -p cre
…
…
your example does not seem to require the need to save the output of a shell command to a variable.
June 4, 2009 at 5:20 am |
typo error:
it should be:
$ echo “hello” >> $cre/file1
April 2, 2010 at 12:08 am |
[…] this does is say check if system is SunOS, if so, use xterm. I got the ` unix command ` info from here. I got the uname command info from […]
October 6, 2011 at 6:01 pm |
Thanks a ton you made my day š š š