[unix] check if directory exists and delete in one command unix

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...

This question is related to unix

The answer is


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.


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.


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)