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...
Solution 1:
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:
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:
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:
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)