bash 在脚本中的通配符中使用圆括号时,意外标记 `(' 附近出现语法错误
bash syntax error near unexpected token `(' when using parentheses in wildcard in script
我正在尝试 运行 这个脚本:
mkdir a
cd a
touch a1, a2, a_
ls ./a!(_)
echo -e '#!/bin/bash\nls ./a!(_)\n' >> run.sh
chmod a+x run.sh
./run.sh
ls
行按预期打印输出 (./a1, ./a2,
),但脚本失败:
./run.sh: line 2: syntax error near unexpected token `('
./run.sh: line 2: `ls ./a!(_)'
有没有办法在 bash 脚本中使用括号而不使用 find
或 for
?
您需要启用 bash
的 extglob
选项和 shopt -s extglob
才能使用否定模式。
将 echo
行更改为
printf '%s\n' '#!/bin/bash' 'shopt -s extglob' 'ls ./a!(_)' > run.sh
之后您可以使用 shopt -u extglob
禁用扩展通配。
相关:
- Pattern Matching(Bash 手动)
我正在尝试 运行 这个脚本:
mkdir a
cd a
touch a1, a2, a_
ls ./a!(_)
echo -e '#!/bin/bash\nls ./a!(_)\n' >> run.sh
chmod a+x run.sh
./run.sh
ls
行按预期打印输出 (./a1, ./a2,
),但脚本失败:
./run.sh: line 2: syntax error near unexpected token `('
./run.sh: line 2: `ls ./a!(_)'
有没有办法在 bash 脚本中使用括号而不使用 find
或 for
?
您需要启用 bash
的 extglob
选项和 shopt -s extglob
才能使用否定模式。
将 echo
行更改为
printf '%s\n' '#!/bin/bash' 'shopt -s extglob' 'ls ./a!(_)' > run.sh
之后您可以使用 shopt -u extglob
禁用扩展通配。
相关:
- Pattern Matching(Bash 手动)