Command intercept failure
I want to know what to return in the preexec function so that the command will not continue executing. I tried return 1, but the command still executed.
function preexec () { if [[ "${1}" == "rm" ]]; then return 1 fi }
This is a duplicate of #155.
bash-preexec doesn't offer such a feature.
You need to set it up by yourself by overriding "\r" (RET), "\C-o", '"\C-x\C-e"', etc. using e.g. bind -x '"\r": your-function, where "your-function" runs the command only when the condition is met.
The command will be run in an unusual way[^1] with a naive implementation of such a strategy, but if you care about it, you can use @d630's strategy mentioned in https://github.com/rcaloras/bash-preexec/discussions/155#discussioncomment-9054828; you can translate "\r" to a two key sequences by bind -s, and the first key sequence is bound to your function, which determines and overwrites the keybinding for the second key sequence dynamically. If one wants to run the command, one can rebind the second key sequence to accept-line. If one doesn't want to run the command, one can rebind the second key sequence to abort or something. The detailed implementation can be found in the link provided in the original comment: d630/bpx. Or you may totally switch to d630/bpx, though I haven't tried it by myself.
[^1]: The commands will be run inside the function bind -x. Then, it might cause differences in the behavior of the commands. For example, declare var would create a local variable instead of a global one, so the values and attributes set by declare wouldn't be visible in the next execution of the commands. You will need to use declare -g var in the command line. For another example, the TTY state is different so that one may not see user's inputs to some commands, etc. For this one, one needs to save the TTY state by saved=$(stty -g), adjust the TTY state by e.g. stty icrnl icanon echo, run the command, and then restore the saved state by stty "$saved". Another problem is that the command history is not automatically updated. One needs to register a command manually using history -s "$READLINE_LINE". In this case, if you want the filtering by HISTCONTROL and HISTIGNORE, you need to implement them by yourself. Some partial implementation of a function to run the command is available at e.g. atuin.bash, but this is still imperfect solution due to Bash's limitation.
I want to know what to return in the preexec function so that the command will not continue executing. I tried
return 1, but the command still executed.function preexec () {
if [[ "${1}" == *"rm"* ]]; then return 1 fi}