1

I need to execute "rm -rf" on remote machine running Ubuntu in order to clear specified folder. 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. Is there any way to specify path to be handled the same way in bash and PS? Thank you!

1 Answers1

4

tl;dr

Unfortunately, as of PowerShell 7.0, you must do the following (if you want to use the external rm utility):

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.

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 parses "home/blahblah/blah"/* as two arguments:

  • home/blahblah/blah becomes the first argument, as-is in this case.

  • /* 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.

Therefore, the arguments that the rm utility actually receives are: -rf, home/blahblah/blah, /bin, /boot, /dev, ... - which is clearly not the intent.

This problematic behavior is discussed in this GitHub issue.

Passing the command to sh, the default shell on Unix-like platforms, instead, bypasses the problem.

mklement0
  • 382,024
  • 64
  • 607
  • 775