How to save the output of a shell command to a variable

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: , ,

6 Responses to “How to save the output of a shell command to a variable”

  1. nageswararao Says:

    thanq….

  2. Jay Says:

    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?

    • samindaw Says:

      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.

  3. Jay Says:

    typo error:

    it should be:

    $ echo “hello” >> $cre/file1

  4. Run screen in emacs with ansi-term (combine this with emacs + ess + remote R) « Super Nerdy Cool Says:

    […] 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 […]

  5. siddhesh_sawant_andheri Says:

    Thanks a ton you made my day šŸ™‚ šŸ™‚ šŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: