0

I've written the following line of code to delete the contents of a directory.

rm -rf $dir && mkdir -p $dir

However, this will not work if the first statement failed. Does it ever return 1?

3
  • 1
    For what it is worth, this is very dangerous code. Make sure you sanitize the $dir variable and handle it if it is not set.
    – 111---
    Dec 12 '16 at 17:02
  • Considering the desired end state with rm -rf <dir> is to clear out anything that's there, is it really an error? The assumption you're going into mkdir with is still true if it wasn't there to begin with. If it really bothers you, you can remove -f which won't ignore non-existent files.
    – Bratchley
    Dec 12 '16 at 17:02
  • I would at the very least do two sanity checks: if [[ "/" != "$dir ]] && [[ -d "$dir" ]]; then rm -fr "$dir"; fi. But having an rm -fr $var is exceedingly dangerous and you should look very carefully at whether there is any other way to do what you are trying to do.
    – DopeGhoti
    Dec 12 '16 at 17:17
2

Sure, if some part of the deletion would violate permissions. For example

$ mkdir -p p/q
$ sudo chown root p p/q
$ sudo chmod 700 p p/q
$ rm -rf p
rm: cannot remove 'p': Permission denied
$ echo $?
1

Note, however, that you can remove a directory that's not yours from a directory that is. So the above would not fail if I only tried with p without the "contents".

2

Yes, if you don't have permission to remove $dir the rm will fail, with -r I assume it will fail if anything at all cannot be deleted.

For example,

$ mkdir test_dir
$ sudo chown root.root test_dir
$ cd test_dir # we no longer have write permission to .
$ sudo mkdir new_dir
$ rm -rf new_dir
rm: cannot remove 'new_dir': Permission denied
$ echo $?
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.