首页 > 解决方案 > Bash 命令在终端中运行,但不在脚本文件中

问题描述

我正在尝试从目录中删除一些文件和文件夹。命令(从这里):

rm -rf !(file_i_don't_want_to_remove|other|other_one)

在终端中运行良好,但如果我尝试在脚本中使用它(使用 vim 创建,2 行):

#!/bin/bash
rm -rf !(one|two)

./file.sh: línea 2: error sintáctico cerca del elemento inesperado `('

翻译:

./file.sh:第 2 行:意外元素 `(' 附近的语法错误

为什么?

PS。我一直在寻找具有相同名称的其他问题,但它们对于每个脚本来说都太具体了,而且似乎与我的问题不同。

标签: bash

解决方案


您需要extglob启用此语法的扩展才能工作:

#!/bin/bash
shopt -s extglob
cd /path/to/dir # See the comment below the answer
rm -rv !(one|two)

PS:请勿rm -f脚本中使用。

PS:如果/path/to/dir来自变量,请确保在使用它之前不为空cd

if [ -z "${path_to_delete}" ] ; then
    "path_to_delete is empty! Aborting"
    exit 1
fi
cd "${path_to_delete}"
rm -rv !(one|two)

推荐阅读