check if directory exists and delete in one command unix

Unix

Unix Problem Overview


Is it possible to check if a directory exists and delete if it does,in Unix using a single command? I have situation where I use ANT 'sshexec' task where I can run only a single command in the remote machine. And I need to check if directory exists and delete it...

Unix Solutions


Solution 1 - Unix

Why not just use rm -rf /some/dir? That will remove the directory if it's present, otherwise do nothing. Unlike rm -r /some/dir this flavor of the command won't crash if the folder doesn't exist.

Solution 2 - Unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

Solution 3 - Unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Solution 4 - Unix

Here is another one liner:

[[ -d /tmp/test ]] && rm -r /tmp/test
  • && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero)

Solution 5 - Unix

I recommend opening documentation of rm command. If open then you will see that there is a -f flag does what you want. Example: rm -f -R ./my_folder

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionremoView Question on Stackoverflow
Solution 1 - UnixDominic MitchellView Answer on Stackoverflow
Solution 2 - UnixNick GrealyView Answer on Stackoverflow
Solution 3 - UnixsinelawView Answer on Stackoverflow
Solution 4 - UnixAkhilesh JoshiView Answer on Stackoverflow
Solution 5 - UnixKonstantin BurlachenkoView Answer on Stackoverflow