Home > Software engineering >  Why “echo -e a\ b\ c” interprets '\' escapes but “echo -e $(cat file)” does not?
Why “echo -e a\ b\ c” interprets '\' escapes but “echo -e $(cat file)” does not?

Time:01-26

In the linux command line, one can use the syntax command1 $(command2) to have the output of command2 be used as arguments for command1. For example, if I have a file test.txt with content this\ is\ a\ test, I can use (which in this case is nonsense) echo $(cat test.txt) to echo the output of cat test.txt. However, this interprets escape sequences in a weird way: The output of the command echo -e this\ is\ a\ test is this is a test, while the output of echo -e $(cat test.txt) is this\ is\ a\ test. The escape sequences are not interpreted as such. Does anyone have any idea why this is?

CodePudding user response:

Use set -x to see the difference:

$ cat file
this\ is\ a\ test
$ set -x
$ echo -e this\ is\ a\ test
  echo -e 'this is a test'
this is a test
$ echo -e 'this\ is\ a\ test'
  echo -e 'this\ is\ a\ test'
this\ is\ a\ test
$ echo -e $(cat file)
   cat file
  echo -e 'this\' 'is\' 'a\' test
this\ is\ a\ test
  •  Tags:  
  • Related