bash: how to pass command line arguments containing special characters

I've written myself a linux program program that needs a regular expression as input.

I want to call the program in the bash shell and pass that regular expression as a command line argument to the program (there are also other command line arguments). A typical regular expression looks like

[abc]\_[x|y]

Unfortunately the characters [, ], and | are special characters in bash. Thus, calling

program [abc]\_[x|y] anotheragument

doesn't work. Is there a way to pass the expression by using some sort of escape characters or quotation marks etc.?

(Calling program "[abc]\_[x|y] anotheragument" isn't working either, because it interprets the two arguments as one.)


Solution 1:

You can either:

  1. Escape each single special symbol with a backslash (as in \[abc\]_\[x\|y\]) or
  2. Double-quote the entire argument (as in "[abc]_[x|y]").

EDIT: As some have pointed out, double-quoting does not prevent variable expansion nor command substitution. Therefore if your regex contains something that can be interpreted by bash as one of those, use single quotes instead.

Solution 2:

Use single quotes. Single quotes ensure that none of the characters are interpreted.

$ printf %s 'spaces  are  not  interpreted away
neither are new lines
nor variable names $TESTING
nor square brackets [TESTING]
nor pipe characters or redirection symbols | > <
nor the semicolon ;
nor backslashes \a \b \c \\
the only thing that does not work is the single quote itself
'

There are two solutions if you need to embed a single quote:

$ printf '%s\n' '[ Don'"'"'t worry, be happy! ]'
[ Don't worry, be happy! ]
$ printf '%s\n' '[ Don'\''t worry, be happy! ]'
[ Don't worry, be happy! ]