Home > Software design >  What does \( mean in a bash script
What does \( mean in a bash script

Time:10-06

I am editing someone else's .sh, and I came across this line

if [ "$ACTION" = "install" -o \( "$ACTION" = "start" -a -z "$APPS" \) ]

What I understand:

  • "$ACTION" = "install" is checking if the script's action is to install
  • -o is the OR operator
  • "$ACTION" = "start" is checking if the script is starting another program
  • -a is the AND operator
  • -z "$APPS" is checking if $APPS is an empty string

I don't know what \( "$ACTION" = "start" -a -z "$APPS" \) means. Is the backslash parenthesis ( \( <action> \) ) a start/end comment? I looked here and this is not the normal conditional grouping that I would expect.

EDIT: To help represent what I thought was going on, this is the equivalent in most other programing languages. Because I am fairly new to bash, the open ended || didn't seem weird to me.

if (ACTION == 'install' || /* ACTION == 'start' && APPS == '' */)

CodePudding user response:

\( escapes the character ( so it isn't treated as syntax by the shell and is instead passed as an argument to test (aka [). You could achieve the same effect with '(' or "(" as well.

Note that use of parenthesis for grouping (and all other cases where more than one test operation is performed per test invocation -- meaning -a and -o as well) is marked obsolescent in the POSIX standard for test, and should not be used in new code (see the OB markers in the standards document).

A better way to write this would be:

if [ "$ACTION" = "install" ] || { [ "$ACTION" = "start" ] && [ -z "$APPS" ]; }; then

...or, using [[ (a ksh and bash extension that provides parser support, making quotes unnecessary in most positions and allowing ( and ) to be parsed as part of the test operation without escaping needed):

if [[ $ACTION = install || ( $ACTION = start && -z $APPS ) ]]; then
  • Related