Bash命令在终端中运行,但不在脚本文件中运行 [英] Bash command runs in terminal but not in script file
问题描述
我正在尝试从目录中删除一些文件和文件夹.命令(来自此处):
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)
在终端上运行正常,但是如果我尝试在脚本(使用vim创建的两行代码)中使用它:
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:时间2:错误sinácticocerca del elemento inesperado`('
./file.sh: línea 2: error sintáctico cerca del elemento inesperado `('
翻译:
./file.sh:第2行:意外错误'('
./file.sh: line 2: syntax error near of unexpected element `('
为什么?
PS.我一直在寻找其他同名的问题,但是它们对于每个脚本来说都太具体了,似乎与我的问题不一样.
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.
推荐答案
您需要 extglob
扩展启用后,此语法才能起作用:
You need the extglob
extension enabled for this syntax to work:
#!/bin/bash
shopt -s extglob
cd /path/to/dir # See the comment below the answer
rm -rv !(one|two)
PS:请不要在脚本中使用rm -f
.
PS: Do not use rm -f
in a script.
PS:如果/path/to/dir
来自变量,请确保该值不为空,然后将其与cd
一起使用:
PS: If /path/to/dir
is coming from a variable, make sure that is is not empty before using it with cd
:
if [ -z "${path_to_delete}" ] ; then
"path_to_delete is empty! Aborting"
exit 1
fi
cd "${path_to_delete}"
rm -rv !(one|two)
这篇关于Bash命令在终端中运行,但不在脚本文件中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!