user2305125
user2305125

Reputation: 51

Echo woes with variable expansion

I want to append the string PROMPT_COMMAND='echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\"' to the end of a .bashrc file across 4300 servers.

I'm having some difficulty in escaping, obviously I want the variables to not expand when being appended to the file so that the text is kept original.

How might I do so? I tried adding slashes to the beginning of the variables, but that didn't seem to be what I wanted.

Upvotes: 2

Views: 107

Answers (3)

Zombo
Zombo

Reputation: 1

Might be better to use a heredoc

cat >> .bashrc <<'+'
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
+

Upvotes: 4

that other guy
that other guy

Reputation: 123410

Here's the general solution for when you want a verbatim value in a command line but don't know how to quote it:

Put your value in a file exactly the way you want it:

$ cat file
PROMPT_COMMAND='echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\"'

Use printf to automatically escape it:

$ printf "echo %q\n" "$(< file)"
echo PROMPT_COMMAND=\'echo\ -ne\ \\\"\\033\]0\;\$\{USER\}@\$\{HOSTNAME\}:\ \$\{PWD\}\\007\\\"\'

The resulting command produces the same result as the file, with all special characters and non-trailing line feeds intact:

$ echo PROMPT_COMMAND=\'echo\ -ne\ \\\"\\033\]0\;\$\{USER\}@\$\{HOSTNAME\}:\ \$\{PWD\}\\007\\\"\'
PROMPT_COMMAND='echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\"'

Important things to note:

  1. You would do this once, interactively, to generate the echo command to use. The suggested answer is NOT to create the temporary file on each of the 4300 machines.

  2. It's bash specific, and so is the command it produces.

  3. If you use ssh, you need a separate layer of escaping.

Upvotes: 3

iruvar
iruvar

Reputation: 23374

Try bash $ quoting

echo $'PROMPT_COMMAND=\'echo -ne \\\"\\033]0;${USER}@${HOSTNAME}: ${PWD}\\007\\\"\''
PROMPT_COMMAND='echo -ne \"\033]0;${USER}@${HOSTNAME}: ${PWD}\007\"'

Upvotes: 2

Related Questions