首页 > 解决方案 > 在 bash 脚本中添加 '(' 字符的 bash 语法错误

问题描述

我在 Linux 命令行上运行以下命令

cp !(non_*).txt some_folder/

它按预期工作(即,将当前文件夹中以“non_”开头的文件除外的所有 *.txt 文件复制到 some_folder。)

但是当将同一行添加到脚本文件并执行它时 ./script.sh

它抛出以下错误。

./script.sh: line 1: syntax error near unexpected token `('

./script.sh: line 1: ` cp !(oam_cfg*).txt kk/'

这里有什么更正?

仅供参考:我正在尝试将当前文件夹中以“non_”开头的文件除外的所有 *.txt 文件复制到 some_folder。

标签: bashshellwildcard

解决方案


正如 Jetchisel 一小时前评论的那样,您需要打开扩展通配符。

一个例子:

$: touch foo.txt bar.txt  # create a file
$: echo +(foo*txt)        # use an extended glob, which fails on syntax
bash: syntax error near unexpected token `('
$: shopt -s extglob  # turn extended globbing *ON*
$: echo +(foo*txt)   # same command now succeeds
foo.txt
$: echo !(foo).txt   # negative works as well
bar.txt

推荐阅读