6

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.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
test
  • 579
  • 1
  • 6
  • 13

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
  • 46,064
  • 19
  • 123
  • 136
  • 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,341
  • 1
  • 26
  • 27