Var*_*Agw 4 linux bash shell-script
我正在尝试创建一个需要此类功能的程序。流程将如下所示:
有没有办法做到这一点?
注意:我需要这个供我个人使用,我不打算分发这个程序。
Var*_*Agw 12
我对此做了一些研究。我们可以使用 bashTRAP
和shopt
option 来实现这一点。
将此添加到 .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)