remo
remo

Reputation: 3484

Check if directory exists and delete in one command

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.

Upvotes: 201

Views: 247626

Answers (5)

Konstantin Burlachenko
Konstantin Burlachenko

Reputation: 5665

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

Upvotes: 4

sinelaw
sinelaw

Reputation: 16553

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.

Upvotes: 40

Akhilesh Joshi
Akhilesh Joshi

Reputation: 362

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)

Upvotes: 16

Dominic Mitchell
Dominic Mitchell

Reputation: 12289

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.

Upvotes: 319

Nick Grealy
Nick Grealy

Reputation: 25864

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)

Upvotes: 235

Related Questions