Skip to content

Instantly share code, notes, and snippets.

@aoyama-val
Created May 1, 2018 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aoyama-val/da042e1d0a8a95e6349aeaba8a5b54c3 to your computer and use it in GitHub Desktop.
Save aoyama-val/da042e1d0a8a95e6349aeaba8a5b54c3 to your computer and use it in GitHub Desktop.
I believe most Unix users have experiences in their newbie days in which they did something like `sed -e "s/foo/bar/g" infile > infile` and overwritten invaluable files. This zsh function prevents it. Unlike 'setopt noclobber', it refuses to execute the command line only when the destination filename appears before the redirect sign (>).
accept-line-smart-no-clobber() {
setopt localoptions noksharrays
local words=("${(z)BUFFER}")
local last_word="${words[$#words]}"
local last_word2="${words[$(($#words - 1))]}"
if [ "$last_word2" = ">" -a -e "$last_word" ]; then
for (( i = 1; i <= $#words - 2; i++ )); do
local w="${words[$i]}"
if [ "$w" = "$last_word" ]; then
zle -M "Destination file already exists. If you want to overwrite it, use '>|' instead of '>'."
return 1
fi
done
fi
zle accept-line
}
zle -N accept-line-smart-no-clobber
bindkey "^m" accept-line-smart-no-clobber
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment