[英]Using 'rm -rf' in Linux PowerShell and Linux bash
I need to execute "rm -rf" on remote machine running Ubuntu in order to clear specified folder.我需要在运行 Ubuntu 的远程计算机上执行“rm -rf”以清除指定文件夹。 If I use command like following everything goes fine.
如果我使用如下命令,一切都会好起来的。
rm -rf "home/blahblah/blah"/*
But if I run the same command in Linux PowerShell I would get ALL files removed.但是,如果我在 Linux PowerShell 中运行相同的命令,我会删除所有文件。 Is there any way to specify path to be handled the same way in bash and PS?
有没有办法在 bash 和 PS 中指定要以相同方式处理的路径? Thank you!
谢谢!
tl;dr tl;博士
Unfortunately, as of PowerShell 7.0, you must do the following (if you want to use the external rm
utility):不幸的是,从 PowerShell 7.0 开始,您必须执行以下操作(如果您想使用外部
rm
实用程序):
sh -c "rm -rf 'home/blahblah/blah'/*"
Note that I've switched to single-quoting ( '...'
) around the path, so I could use it inside a double-quoted ( "..."
) string.请注意,我已切换到路径周围的单引号 (
'...'
),因此我可以在双引号 ( "..."
) 字符串中使用它。 While the reverse ( '... "..."/*'
) should work as-is, it currently requires additional escaping ( '... \"...\"/*'
) - see this answer .虽然反向(
'... "..."/*'
)应该按原样工作,但它目前需要额外的 escaping ( '... \"...\"/*'
) - 请参阅此答案。
However, if the path preceding the /*
doesn't actually need quoting - notably if it doesn't contain spaces - you can simply call:但是,如果
/*
之前的路径实际上不需要引用- 特别是如果它不包含空格 - 你可以简单地调用:
rm -rf home/blahblah/blah/*
You're seeing a very unfortunate difference between PowerShell (as of 7.0) and POSIX-like shells such as Bash with respect to the handling of string arguments composed of both quoted and unquoted parts.您会看到 PowerShell(自 7.0 起)和类似 POSIX 的 shell(如 Bash)在处理字符串 arguments 方面存在非常不幸的区别
PowerShell parses "home/blahblah/blah"/*
as two arguments: PowerShell 将
"home/blahblah/blah"/*
解析为两个arguments:
home/blahblah/blah
becomes the first argument, as-is in this case. home/blahblah/blah
成为第一个参数,在这种情况下也是如此。
/*
is interpreted as the second argument, which, due to being unquoted and due to an external utility being called, triggers PowerShell's emulation of the globbing (filename expansion) behavior of POSIX-like shells, which means that all files and directories in the root directory are being passed as individual arguments. /*
被解释为第二个参数,由于未引用并且由于调用了外部实用程序,它会触发 PowerShell 对类 POSIX 外壳的通配(文件名扩展)行为的模拟,这意味着根目录作为单独的 arguments 传递。
Therefore, the arguments that the rm
utility actually receives are: -rf
, home/blahblah/blah
, /bin
, /boot
, /dev
, ... - which is clearly not the intent.因此,
rm
实用程序实际收到的 arguments 是: -rf
、 home/blahblah/blah
、 /bin
、 /boot
、 /dev
…… - 这显然不是本意。
This problematic behavior is discussed in this GitHub issue .此问题行为在此 GitHub 问题中进行了讨论。
Passing the command to sh
, the default shell on Unix-like platforms, instead, bypasses the problem.将命令传递给
sh
,类 Unix 平台上的默认 shell 反而绕过了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.