RM失败时从脚本通配符来删除文件,而是从shell提示下工作 [英] rm fails to delete files by wildcard from a script, but works from a shell prompt

查看:711
本文介绍了RM失败时从脚本通配符来删除文件,而是从shell提示下工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到一个Linux的shell脚本一个非常愚蠢的问题。我想删除与目录中的扩展名,操作.bz2的所有文件。在剧本我称之为

I've run into a really silly problem with a Linux shell script. I want to delete all files with the extension ".bz2" in a directory. In the script I call

rm "$archivedir/*.bz2"

其中$ archivedir是一个目录路径。应该是pretty简单,不应该吗?不知何故,它管理的失败,此错误:

where $archivedir is a directory path. Should be pretty simple, shouldn't it? Somehow, it manages to fail with this error:

rm: cannot remove `/var/archives/monthly/April/*.bz2': No such file or directory

的在该目录中名为test.bz2一个文件,如果我改变我的脚本

But there is a file in that directory called test.bz2 and if I change my script to

echo rm "$archivedir/*.bz2"

和复制/该行的输出粘贴到一个终端窗口中的文件被成功删除。我在做什么错了?

and copy/paste the output of that line into a terminal window the file is removed successfully. What am I doing wrong?

推荐答案

要扩大多一点:


  • 在Unix中,程序一般不跨preT通配符自己。外壳间$ P $点不带引号的通配符,并替换匹配的文件名列表中的每个通配符参数。
    如果$ archivedir可能包含空格,则 RM $ archivedir / *。BZ2 可能不会做你

您可以通过引用通配符,使用双或单引号,或前一个反斜杠禁用此过程。然而,这不是你想要的这里 - 你想扩展到文件列表中的通配符,它​​匹配

You can disable this process by quoting the wildcard character, using double or single quotes, or a backslash before it. However, that's not what you want here - you do want the wildcard expanded to the list of files that it matches.

要小心写 RM $ archivedir / *。BZ2 (不带引号)。这个词拆分(即,打破了命令行成参数)发生的之后的$ archivedir被取代。所以,如果$ archivedir包含空格,那么你会得到你不打算额外的参数。说archivedir是的/ var /档案馆/每月/四月到六月。然后你会得到书面相当于 RM的/ var /档案馆/每月/四月它试图删除文件六月/ *。BZ2 ,在/ var /档案馆/每月/月,来,和匹配所有文件六一/ *。BZ2,这是不是你想要的。

Be careful about writing rm $archivedir/*.bz2 (without quotes). The word splitting (i.e., breaking the command line up into arguments) happens after $archivedir is substituted. So if $archivedir contains spaces, then you'll get extra arguments that you weren't intending. Say archivedir is /var/archives/monthly/April to June. Then you'll get the equivalent of writing rm /var/archives/monthly/April to June/*.bz2, which tries to delete the files "/var/archives/monthly/April", "to", and all files matching "June/*.bz2", which isn't what you want.

正确的解决办法是写:

rm "$archivedir"/*.bz2

这篇关于RM失败时从脚本通配符来删除文件,而是从shell提示下工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆