18

If I use single quotes, words with apostrophes ("don't") are annoying to escape:

'Don'"'"'t do that'

If I use double quotes, dollar signs and exclamation points trip it up:

"It cost like \$1000\!"

Is there another kind of quoting I can use?

edit: I should also add that I would like to pass this string directly as a command line argument, rather than storing it in a variable. To this end I tried, using DigitalRoss's solution,

$ echo "$(cat << \EOF 
Don't $worry be "happy".
EOF)"

but get

dquote cmdsubst> 

after hitting enter :/ . So at this point ZyX's suggestion of setopt rcquotes looks to be the most convenient.

Owen
  • 38,836
  • 14
  • 95
  • 125

4 Answers4

24

With zsh you may do

setopt rcquotes

. Then ASCII apostrophes are escaped just like this:

echo 'Don''t'

. Or setup your keymap to be able to enter UTF apostrophes, they have no issues with any kind of quotes (including none) in any shell:

echo 'Don’t'

. Third works both for zsh and bash:

echo $'Don\'t'

.

Neither first nor third can narrow down quote to a single character, but they are still less verbose for non-lengthy strings then heredocs suggested above. With zsh you can do this by using custom accept-line widget that will replace constructs like 'Don't' with 'Don'\''t'. Requires rather tricky regex magic that I can write only in perl; and is probably not the best idea as I can’t pretend I can cover all possible cases before they will hit. It won’t in any case touch any scripts.

ZyX
  • 52,536
  • 7
  • 114
  • 135
4

I like the direction Zsolt Botykai is going. Here is an example that works with any Posix shell. (I also verified that it survived its paste into the SO server.)

$ read -r x << \EOF
Don't $worry be "happy".
EOF
$ echo $x
Don't $worry be "happy".

The things that make this work;

  • -r will make \ not be magic
  • the \EOF instead of just EOF makes $ not be magic
Community
  • 1
  • 1
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
3

If you want to assign a quoted text to a variable, you still can use heredocs, like (and it can be a multiline text too):

read -r -d '' VAR <<'ENDOFVAR'
This "will be" a 'really well' escaped text. Or won't.
ENDOFVAR
Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110
1

Bash syntax $'string' is another quoting mechanism which allows ANSI C-like escape sequences and do expansion to single-quoted version.

$> echo $'Don\'t $worry be "happy".'
Don't $worry be "happy".

See https://stackoverflow.com/a/16605140/149221 for more details.

mj41
  • 2,459
  • 2
  • 16
  • 10