trying to escape quotes

I have tried numerous ways to print this line in a script:

alias myname='export PATH="/path/to/bin:$PATH"'

All of them have different problems.

The last I tried (and remember!) is:

printf '%s' '%sn' 'alias myname=' '''"export PATH="/path/to/bin:$PATH"" '''  >> ~/.bashrc

but it doesn’t work , it prints many times the PATH directory and in front of alias myname has %sn

(I prefer to use printf)

Answer

If I understand the question properly, you’re trying to add the line

alias myname='export PATH="/path/to/bin:$PATH"'

to your ~/.bashrc file

The obvious type of echo will fail because $PATH is expanded at the wrong time.

Instead we need to do some quote mixing:

echo "alias myname='export PATH="/path/to/bin:$PATH"'" >> ~/.bashrc

Now you say, for some reason, you want to use printf. So we can do similar:

printf "%sn" "alias myname='export PATH="/path/to/bin:$PATH"'" >> ~/.bashrc

If you want to treat the two sides of the = as separate strings:

printf "%s=%sn" "alias myname" "'export PATH="/path/to/bin:$PATH"'" >> ~/.bashrc

And so on.

(printf only takes one format argument and then a list of values).

Leave a Reply

Your email address will not be published. Required fields are marked *