Eu fiz algumas pesquisas sobre isso. Podemos usar a opção bash TRAP
e shopt
para conseguir isso.
Adicione isto ao .bash_profile
shopt -s extdebug
preexec_invoke_exec () {
[ -n "$COMP_LINE" ] && return # do nothing if completing
[ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # don't cause a preexec for $PROMPT_COMMAND
local this_command='HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"';
# So that you don't get locked accidentally
if [ "shopt -u extdebug" == "$this_command" ]; then
return 0
fi
# Modify $this_command and then execute it
return 1 # This prevent executing of original command
}
trap 'preexec_invoke_exec' DEBUG
Funciona assim:
trap 'function_name' DEBUG
faz com que function_name
seja executado antes de executar comandos bash. Mas, por padrão, return
value não tem efeito sobre o comando original.
shopt -s extdebug
habilita alguns recursos de depuração com um deles verifica o valor de retorno antes de executar o comando original.
Nota: shopt -u extdebug
desabilita esse recurso para que o comando original sempre seja executado.
Documentação de extdebug
(Veja o segundo recurso):
If set, behavior intended for use by debuggers is enabled:
The -F option to the declare builtin (see Bash Builtins) displays the source file name and line number corresponding to each function name supplied as an argument.
If the command run by the DEBUG trap returns a non-zero value, the next command is skipped and not executed.
If the command run by the DEBUG trap returns a value of 2, and the shell is executing in a subroutine (a shell function or a shell script executed by the . or source builtins), a call to return is simulated.
BASH_ARGC and BASH_ARGV are updated as described in their descriptions (see Bash Variables).
Function tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the DEBUG and RETURN traps.
Error tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the ERR trap.