Bash: Remove file and folder with Windows style directory names and backslashes

The Problem

While working with zip files in WordPress (I’m setting up my own update server and package update process), I manually created a zip file in using 7zip in Windows (my primary operating system) and extracted it via PHP in a Codeanywhere Ubuntu workspace.

The problem was the zip file was created containing Windows paths, so I ended up file with a file name “vylesk-test-plugin\vylesk-test-plugin.txt” and directory name “D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\“.
Notice the backslashes and “D:” drive path.

Removing the file and directory was a problem.

Attempting to perform a simple rm and rm -rf resulted in:

rm: cannot remove './vylesk-test-plugin\vylesk-test-plugin.txt': Permission denied
rm: cannot remove '_temp/vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Permission denied

I tried changing file permissions using chmod and that also resulted in:

chmod: changing permissions of 'vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Operation not permitted
chmod: changing permissions of 'vylesk-test-plugin.1.1/vylesk-test-plugin\vylesk-test-plugin.txt': Operation not permitted


The Solution

The solution turned out to be very simple. I just needed to prefix the command with sudo.

So I ended up with:

sudo rm vylesk-test-plugin\\vylesk-test-plugin.txt
sudo rm -rf 'D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\'

The file and directory then deleted successfully (and I didn’t need an su password, which I don’t know anywhere because it’s in a virtual environment I don’t control).

Note 2 other elements of the commands:

  • In the first ‘rm’ line the “\\” (double-backslash), because backslashes need to be escaped.
  • In the second line I surrounded the directory path with single quotes, an alternative to the double-backslash.