3

The command echo Hello World, prints Hello World as expected, but echo Hello (World) generates the error syntax error near unexpected token `('.

I'm aware that brackets such as (), {}, [] are tokens and have a special meaning, so how do you "escape" these in a bash script?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
AlainD
  • 141
  • 1
  • 7
  • 2
    Possible duplicate of [How can I echo dollar signs?](https://unix.stackexchange.com/questions/162476/how-can-i-echo-dollar-signs) Or [How do I handle special characters like a bracket in a bash script?](https://unix.stackexchange.com/questions/173851/how-do-i-handle-special-characters-like-a-bracket-in-a-bash-script) – muru Oct 21 '19 at 10:11
  • @Ah yes, those appear to be duplicate, thanks. Would be nice for a combined answer because there appear to be multiple answers: single quotes around whole string, double quotes around whole string, single quote around the special characters and backslash, as in `\(`, and so on. – AlainD Oct 21 '19 at 10:17

2 Answers2

15

They're not actually tokens in the lexer sense, except for the plain parenthesis ( and ).

{ and } in particular don't need any quoting at all:

$ echo {Hello World}
{Hello World}

(except if you have { or } as the first word of a command, where they're interpreted as keywords; or if you have {a,b} in a single word with a comma or double-dot in between, where it's a brace expansion.)

[] is also only special as a glob characters, and if there are no matching filenames, the default behaviour is to just leave the word as-is.

But anyway, to escape them, you'd usually quote them with single or double-quotes:

echo "(foo bar)"
echo '(foo bar)'

Or just escape the relevant characters one-by-one, though that's a bit weary:

echo \(foo\ bar\)

Or whatever combination you like:

echo \(fo"o bar"')'

See:

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
0

Specific to the Q: real "escaping" would be:

echo hello \(world\)

A "clean" call of echo with one shell argument is:

echo "hello (world)"

...and you get the "escaping" for free.

echo hello "("world")"

is quite undefinable. And so on. "you can play with echo".

"hello $world" and

'hello $world'

are not the same! Use world=mars first.

  • 1
    What do you mean by "undefinable"? `echo hello "("world")"` is quite well defined, being equivalent to `echo hello \(world\)`. – chepner Oct 21 '19 at 19:04
  • @chepner Are the parens escaped or quoted? escaped by quoting? You are right, I did not mean the result when I said undefinable. –  Oct 21 '19 at 19:41
  • Quoting is just a form of mass escaping. Inside double quotes, each character is treated as if it were escaped, with the exception of `$` (and any following characters that form a valid parameter name), `"`, and backslash – chepner Oct 21 '19 at 19:44