I have a directory whose name contains spaces. I need to remove the contents of this particular directory.
I am escaping spaces in the directory name with \
before removing the contents.
The rm
command works fine from terminal however it doesn't work if I use it in Shell script. I get No such file or directory error.
For e.g. I have following directory structure
Users/Neeraj/Documents/temp dir/dir with spaces/a.txt
I need to remove everything inside directory "dir with spaces". The code in my Shell scripts looks like
#!/bin/sh
TEMP_DIR="$HOME/Documents/temp dir/dir with spaces"
TEMP_DIR=$(echo $TEMP_DIR | sed 's/ /\\ /g')
COMMAND="rm -r $TEMP_DIR/*"
echo "Command: $COMMAND"
rm -r "$TEMP_DIR"/*
When I run this script, I get No such file or directory error while the same command works fine if I just copy it and run from the terminal.
Output:
Command: rm -r /Users/Neeraj/Documents/temp\ dir/dir\ with\ spaces/*
rm: /Users/Neeraj/Documents/temp\ dir/dir\ with\ spaces/*: No such file or directory
What is the correct way to do this?
Note: I am using macOS