Bash command runs in terminal but not in script file

时间:2018-12-03 13:21:10

标签: bash

I'm trying to delete some files and folders from a directory. The command (from here):

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

Runs fine in terminal, but if I try to use it inside a script (created using vim, 2 lines):

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

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

Translated:

./file.sh: line 2: syntax error near of unexpected element `('

Why?

PS. I've looked for other questions with the same name but they're all too specific for each script and seem not to be the same problem than mine.

1 个答案:

答案 0 :(得分:4)

您需要启用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)