在执行之前通过程序修改所有 bash 命令

Var*_*Agw 4 linux bash shell-script

我正在尝试创建一个需要此类功能的程序。流程将如下所示:

  • 用户输入 bash 命令
  • 用户按下回车键
  • 我的脚本将获取命令、当前目录等作为变量。程序可以随意修改命令。
  • 修改后的命令会正常执行。

有没有办法做到这一点?

注意:我需要这个供我个人使用,我不打算分发这个程序。

Var*_*Agw 12

我对此做了一些研究。我们可以使用 bashTRAPshoptoption 来实现这一点。

将此添加到 .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
Run Code Online (Sandbox Code Playgroud)

它是这样工作的:

trap 'function_name' DEBUG导致function_name在执行 bash 命令之前执行。但默认return值对原始命令没有影响。

shopt -s extdebug 启用一些调试功能,其中之一在执行原始命令之前检查返回值。

注意:shopt -u extdebug禁用此功能,以便始终执行原始命令。

文档extdebug(见第二个功能):

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.
Run Code Online (Sandbox Code Playgroud)