alvas
alvas

Reputation: 122052

Escape special characters in echo

http://www.grymoire.com/Unix/Quote.html shows a list of special characters. Is there a parameter/option for echo where I can treat everything that comes after the echo as a string?

In python, i could use the """...""" or '''...'''.

$ python
>>> text = '''#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&'''
>>> print text
#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&

I can do the same in unix's echo with ''' but not """, why is that so?

$ echo #"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&

$ echo '''#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&'''
#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&

$ echo """'''#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&"""
bash: !@#@%$#$^%$: event not found

What happens if i have a string like this?

#"`\|^!@#@%$#$^%'''$&%^*()?/\;:$#$"""@$?$$$!&&

How should I echo such a string? (the following command doesn't work)

echo '''#"`\|^!@#@%$#$^%'''$&%^*()?/\;:$#$"""@$?$$$!&&'''

Upvotes: 2

Views: 17471

Answers (2)

devnull
devnull

Reputation: 123508

Use printf:

$ printf "%s\n" $'#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&'
#"`\|^!@#@%$#$^%$&%^*()?/\;:$#$@$?$$$!&&
$ printf "%s\n" $'#"`\|^!@#@%$#$^%\'\'\'$&%^*()?/\;:$#$"""@$?$$$!&&'
#"`\|^!@#@%$#$^%'''$&%^*()?/\;:$#$"""@$?$$$!&&

You might note that single quotes ' need to be escaped.

In order to assign the output to a variable:

$ foo=$(printf "%s\n" $'#"`\|^!@#@%$#$^%\'\'\'$&%^*()?/\;:$#$"""@$?$$$!&&')
$ echo $foo
#"`\|^!@#@%$#$^%'''$&%^*()?/\;:$#$"""@$?$$$!&&

Upvotes: 3

Jost
Jost

Reputation: 1569

I think it is because of your shell (bash), which expands/interprets double quotes. This does not apply for single quotes. For details, please have a look at Bash - Shell Expansion.

For the echo command there is the -e option which enables interpretation of backslash escapes - which might help.

Upvotes: 2

Related Questions