assign output of shell command to variable in bash
January 31st, 2007 by Lawrence David
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.
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.
Your example doesn’t work.
Unrecognized command: s/AnGST/.*/AnGST//
find: illegal option — n
find: [-H | -L] path-list predicate-list
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.
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!
Not sure what’s right or wrong — but hey your example worked perfectly for me … my first bash script works
Thanks