开发者

check if directory exists and delete in one command unix

开发者 https://www.devze.com 2023-02-07 08:30 出处:网络
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开发者_StackOverflow中文版 use ANT \'sshexec\' task where I can run only a s

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开发者_StackOverflow中文版 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...


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.


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)


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号