Check if directory exists and delete unix in one command

Is it possible to check if a directory exists and delete, if that happens, on Unix with a single command? I have a situation where I use the ANT 'sshexec' task, where I can only run one command on a remote computer. And I need to check if the directory exists and delete it ...

+43
unix
Jan 30 2018-11-11T00:
source share
3 answers

Why not just use rm -rf /some/dir ? This will delete the directory, if present, otherwise it will do nothing.

+77
Jan 31 '11 at 7:39
source share

Try:

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

EDIT . This will work if you can run bash on a remote computer ....

EDIT 2 . In bash, [ -d something ] checks to see if there is a directory named "something" by returning a success code if it exists and is a directory. Chaining commands with && only starts the second command if the first is successful. Therefore, [ -d somedir ] && command runs the command only if the directory exists.

+22
Jan 30 2018-11-11T00:
source share

Assuming $WORKING_DIR installed in the directory ... this single line file should do this:

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

(otherwise just replace your directory)

+16
Jun 20 '16 at 13:32
source share



All Articles