Search code examples
basharithmetic-expressions

syntax error near unexpected token `(' with "let" command in bash script


I have a bash script as following that generates the accompanying error:

# cat ./a.sh
#!/bin/bash
let C=1+(2)
echo $C
#
# ./a.sh
./a.sh: line 2: syntax error near unexpected token `('
./a.sh: line 2: `let C=1+(2)'

However, it works as expected from the command line:

# let C=1+(2)
# echo $C
3

It also works if I change the "let" expression in the script to the following:

C=$((1+(2)))

My bash version is as follows:

# /bin/bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

The O.S. is CentOS 7.7


Solution

  • Ah, here's the culprit: in an interactive session:

    $ declare -p BASH_VERSINFO
    declare -ar BASH_VERSINFO='([0]="4" [1]="2" [2]="45" [3]="1" [4]="release" [5]="i386-apple-darwin19.5.0")'
    
    $ let C=1+(2) && echo $C
    3
    
    $ shopt -u extglob
    
    $ let C=1+(2) && echo $C
    bash: syntax error near unexpected token `('
    

    +(pattern) is an extended glob pattern, and when extglob is turned off, it's apparently illegal syntax.