Feed on
Posts
Comments

to let the variable ‘j’ equal the output of a shell command, such as find, try:

j=$(find `echo $i | sed ’s/AnGST\/.*/AnGST\//’` -name “*.seq”)

basically, it looks like all you need to do is enclose the command with a dollar-sign and some parentheses.  now, your shell scripts won’t need to be populated by unending lines of pipes.

Stumble it!

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

5 Responses to “assign output of shell command to variable in bash”

  1. on 01 Oct 2007 at 2:41 pm Eric Brunson

    It’s funny that you’ve mixed idioms in your example. You’ve used the preferred $() syntax to enclose a backticked command:

    j=$(find $(echo $i | sed ’s/AnGST\/.*/AnGST\//’) -name “*.seq”)

    would be more consistent. The primary reason $() is preferred to backticks is because they nest easily:

    j=`ls` and j=$(ls) are equivalent, but try writing your example with just backticks. :-)

    Plus, sed (or perl) does not need to use the slash to delimit its substitutions, it can use any other character if you want to use the slash in your matches. You’ll find it’s common for programmers to use the “#” symbol when trying to match forward slashes, so your example would become:

    j=$(find $(echo $i | sed ’s#AnGST/.*#AnGST/#’) -name “*.seq”)

    which I find more readable than the backslashed version, but that could just be me. :-)

    Finally, depending you what your $i’s look like, you may be able to replace $( echo $i | sed ‘…’ ) with $( dirname $i ), but I’m just inferring that from the example, and may not exactly fit the bill.

    I’ll shut up now.

  2. on 07 Apr 2008 at 9:00 pm Josh

    Your example doesn’t work.

    Unrecognized command: s/AnGST/.*/AnGST//
    find: illegal option — n
    find: [-H | -L] path-list predicate-list

  3. on 08 Apr 2008 at 8:11 am Lawrence David

    eric: this is really late, but much thanks for all of those tips!! i’m amazed at how much unix i’ve learned by sharing what little i know about bash!

    josh: don’t try and run what’s within $(). instead, replace what i’ve got with your own commands.

  4. on 25 Jun 2008 at 4:57 pm Itch

    So I googled “bash assign output to variable” and this was the first site. I’m a novice Unix admin, and was looking for a way to automate some things from the command line. This saved me some headache. Thank you!

  5. on 02 Aug 2008 at 9:30 am Jacques

    Not sure what’s right or wrong — but hey your example worked perfectly for me … my first bash script works

    Thanks :-)

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.