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
  • 67,283
  • 35
  • 116
  • 255
AlainD
  • 141

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
  • 138,973
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