Bash命令在终端中运行,但不在脚本文件中运行

编程入门 行业动态 更新时间:2024-10-16 19:26:29
本文介绍了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)

在终端上运行正常,但是如果我尝试在脚本(使用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命令在终端中运行,但不在脚本文件中运行

本文发布于:2023-11-23 19:07:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622557.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:终端   脚本   命令   文件   Bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!