Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
    
Sorry about the formatting - I couldn't get backticks to show up in a code block. –  Andrew Wood Jan 27 '11 at 18:51
add comment

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
    
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 Jan 27 '11 at 20:31
    
However I see putting eval in front of my backticked expression works as I'd like it to –  Andrew Wood Jan 27 '11 at 20:35
    
@ajwood: Let me point out the last paragraph of my answer. (Do not forget quotes. Otherwise stuff breaks.) –  grawity Jan 27 '11 at 20:35
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.