Linux – bash: how to pass command line arguments containing special characters

bashcommand linelinuxspecial 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


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.)

Best Answer

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.