Hacker News new | ask | show | jobs
by sfink 629 days ago
My main safety habit is to avoid slashless paths.

Bad:

    rm *
Okay:

    rm ./*
    rm /tmp/d/*
    rm */deadmeat
    rm d/*
Then again, I commonly use dangerous things like `mv somefile{,.away}` that are easy to get wrong, so maybe don't trust my advice too much.
2 comments

  rm -rf "$TSTDIR"/etc
is pretty dangerous when you forget to set the env var
Fair! Upvoted.

I guess I'm not likely to type that into the shell, or if I do, I then tab-complete to expand it.

I could definitely see myself using that in a shell script, though. I tend to do validity checks there:

    if ! [ -d "$TSTDIR" ]; echo "$TSTDIR not found, stupid" >&2; exit 1; fi
but that's kind of irrelevant, since if I need it to exist then I won't be removing it. Plus, I could totally see myself doing

    if [ -d "$TESTDIR" ]; then
      rm -rf "$TSTDIR"/etc
    fi
In bash, `set -u` or `"${TSTDIR:?Error: TSTSDIR is required.}/etc"` protects from such errors.
My safety technique is to echo the commands before I do the actual commands as a sanity check, e.g.

for i in $(find something); do echo "rm -f $i"; done

(bash example as my TCL is rusty)

Change your do block to `printf %q\ rm -f "$i" ; echo` and it won't lie about spaces. In case HN has "trimmed" my post in some way, as it often does, that's: percent q backslash space space. Works in bash/zsh, but not dash, probably not whatever your sh is. Can make a function of it trivially, but you have to handle the $# -eq 0 case, return whatever printf returns, etc.