Created
May 1, 2018 04:26
-
-
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 (>).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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