What is really happening with bash backticks?

1

I've always thought of backticks in bash as "execute the output of 'some_command'." What is happening in the following... consider a script myscript.pl that prints the following text:

   export PS1="[STRING] $PS1"

If I copy the output from cat file.txt to the command line and execute, "[STRING] " gets added to the front of my prompt.

On the other hand, backtick-ing 'myscript.pl' makes my prompt "[STRING]. What is happening?

Andrew Wood

Posted 2011-01-27T18:50:43.133

Reputation: 1 139

Sorry about the formatting - I couldn't get backticks to show up in a code block. – Andrew Wood – 2011-01-27T18:51:47.660

Answers

4

bash doesn't execute the output of a backtick command, only substitutes it. (The feature is called command substitution after all.)

If the substitution is not double-quoted, word splitting is done to the command's output, but quotes and other special characters are ignored; export PS1="[STRING] $PS1" is simply split by $IFS to:

  • export
  • PS1="[STRING
  • $PS1"

If you want to execute a file's contents, source it:

. ./file.txt

or, non-POSIX:

source ./file.txt

If you want all standard parsing to be applied to a substitution -- for example, a variable -- you can use eval "$commands" or eval "$(foo)" or eval "`foo`". But be very careful with it.

user1686

Posted 2011-01-27T18:50:43.133

Reputation: 283 655

Let me clarify my question. I'm not actually storing commands in a text file, but thought that would be a good way to learn about my problem. I've got a Perl script set up to set up a environment variables. To avoid losing the current environment (not actually the right word - aliases, function, shell variables, etc.) I'm having the script dump changes to the environment, that the user will hopefully be able to apply by using backticks to invoke the script. – Andrew Wood – 2011-01-27T20:31:06.300

However I see putting eval in front of my backticked expression works as I'd like it to – Andrew Wood – 2011-01-27T20:35:09.197

@ajwood: Let me point out the last paragraph of my answer. (Do not forget quotes. Otherwise stuff breaks.) – user1686 – 2011-01-27T20:35:46.157