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' '%s\n' '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)

  • 1
    Why are you using two lots of '%s'? printf takes only one format string, so everything after that is interpreted as a literal (hence %sn appearing in the output). – JigglyNaga Aug 2 '16 at 13:00
  • @JigglyNaga:It doesn't work with one either.I used 2 because I have 2 stings. alias myname and the rest. – George Aug 2 '16 at 13:03

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 "%s\n" "alias myname='export PATH=\"/path/to/bin:\$PATH\"'" >> ~/.bashrc

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

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

And so on.

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

  • :Thanks!Finally!!I saw that $ wants also ``.. – George Aug 2 '16 at 13:08

There are two easy solutions. One is to use a here document instead of quote marks. Use the quoted form of the here document (where the <<EOF part contains a quote character) to turn off variable and command substitution inside the here document.

cat <<\EOF >>~/.bashrc
alias myname='export PATH="/path/to/bin:$PATH"'

The other is to use single quotes around the string you want to print. You can effectively escape a single quote in a single-quoted literal by using '\'' — end the single-quoted literal, append a literal single quote, and start a new single-quoted literal.

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

(You can optimize away the final empty string literal ''.)

On some shells, echo command doesn't print its argument literally, which is why the robust way to print a string is with printf:

printf '%s\n' 'alias myname='\''export PATH="/path/to/bin:$PATH"'\'''

In this specific case, echo works too since the only expansions it performs concern backslashes and a leading -.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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