In my related post many years ago, I found a solution how to comment out "dangerous" commands saved in bash history, so that I do not execute them accidentally.
What would be the best solution to implement the same in zsh ?
Does zsh provide some functionality which I could use for this purpose?
I assume, zsh beieng more flexible, this should be easier in zsh.
For reference, this is what I have been using in bash (based on accepted answer from Stéphane Chazelas):
fixhist() {
local cmd time histnum
cmd=$(HISTTIMEFORMAT='<%s>' history 1)
histnum=$((${cmd%%[<*]*}))
time=${cmd%%>*}
time=${time#*<}
cmd=${cmd#*>}
case $cmd in
(cp\ *|mv\ *|rm\ *|cat\ *\>*|pv\ *|dd\ *)
history -d "$histnum" # delete
history -a
[ -f "$HISTFILE" ] && printf '#%s\n' "$time" " $cmd" >> "$HISTFILE";;
(*)
history -a
esac
history -c
history -r
}
UPDATE 2022-09-05:
The accepted solution works, but has unintended side effect. It messes up with insert-last-word keybinding. Here short illustration:
I use one of my "dangerous" commands:
rm zz
it has been added to history with a comment (as desired):
history
...
# rm zz
Lets just add another command to history
echo foo
And now when I want to cycle through the history with Alt+., I get following results:
echo <Alt> + .
foo
history
# rm zz
instead of being offered zz, I am being offered the whole commented command # rm zz.
How can I fix this ?
rm xx yy zzand why? One could argue that the history should show commands rather than filenames, options or other fragments of past commands.rm xx yy zzthen it will be stored in history as# rm xx yy zz. Cycling back through history withAlt+.should offer mezz.