7

I am trying to get the output of some programs and assign them to variables. I am using backticks to do it, but I can switch to a different method if necessary. What I notice is that often I do not get the expected output in the variable. A simple case is this below. The actual examples I have are more complicated. Whatever the output from the program I'm running in the backticks I want it in the variable. Is that possible?

test=`echo [asdf]`

If I echo $test it shows just a.

test
  • 609

2 Answers2

13
  1. Don't use backticks, use $().
  2. Use single quotes around literal strings and double around variables, so echo "$test".
  3. Don't use echo, use printf.

After all:

    $ test="$(printf '%s' '[asdf]')"
    $ printf "%s\n" "$test"
    [asdf]
jimmij
  • 47,140
  • Yeah I mean the echo was just an example, the actual commands are more complicated. I will try what you suggested, thank you. – test Dec 12 '14 at 01:33
7

The simplest answer is to escape the [ so that it isn't treated as a special pattern character. (The closing ] is treated literally if it isn't preceded by an unquoted [.)

test=$(echo \[asdf])
chepner
  • 7,501