bash 脚本中的 "let" 命令在意外标记 `(' 附近出现语法错误

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

我有一个如下所示的 bash 脚本,它会生成伴随的错误:

# 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)'

但是,它在命令行中按预期工作:

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

如果我将脚本中的“let”表达式更改为以下内容,它也会起作用:

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

我的bash版本如下:

# /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.

O.S。是 CentOS 7.7

啊,罪魁祸首是:在交互式会话中:

$ 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) 是一个 extended glob pattern,当 extglob 关闭时,它显然是非法语法。