bash是否具有在执行命令之前运行的钩子?


111

在bash中,我可以安排运行命令之前要执行的功能吗?

$PROMPT_COMMAND,这是示出了提示,即,只是运行命令后之前执行。

Bash的$PROMPT_COMMAND功能类似于zsh的precmd功能;所以我要寻找的是等同于zsh的bash preexec

应用示例:将终端标题设置为正在执行的命令;自动time在每个命令之前添加。


3
bash版本4.4的PS0行为类似于,PS1但在读取命令之后但在执行之前使用。参见gnu.org/software/bash/manual/bashref.html#Bash-Variables
glenn jackman's

Answers:


93

不是本机的,但是可以使用DEBUG陷阱对其进行破解。该代码的设置preexecprecmd功能类似于zsh。命令行作为单个参数传递给preexec

这是代码的简化版本,用于设置precmd在运行每个命令之前执行的功能。

preexec () { :; }
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]*[ ]*//"`;
    preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG

这个技巧是由于Glyph Lefkowitz ; 感谢bcat查找原始作者。

编辑。可以在以下位置找到Glyph hack的更新版本:https : //github.com/rcaloras/bash-preexec


"$BASH_COMMAND" = "$PROMPT_COMMAND"比较不是为我工作i.imgur.com/blneCdQ.png
laggingreflex

2
我尝试在cygwin上使用此代码。可悲的是,它在那里对性能的影响非常大-运行一个简单的基准命令time for i in {1..10}; do true; done通常需要0.040秒,而在激活DEBUG陷阱后则需要1.400至1.600秒。这会使trap命令在每个循环中执行两次-在Cygwin上,单独执行for sed所需的forking缓慢地慢于大约0.030秒(echo内置和之间的速度差/bin/echo)。也许要记住一些事情。
kdb

2
@kdb叉的Cygwin性能糟透了。我的理解是,这在Windows上是不可避免的。如果您需要在Windows上运行bash代码,请尝试减少分叉。
吉尔斯(Gilles)

@DevNull可以很容易地通过删除陷阱来规避。对于人们允许他们做但不应该做的事情,没有任何技术解决方案。有部分补救措施:不要给尽可能多的人访问,确保备份是最新的,使用版本控制而不是直接的文件操作,…如果您想要用户不容易禁用的功能,请让仅凭它根本无法禁用,那么shell中的限制将无济于事:可以像添加它们一样轻松地删除它们。
吉尔斯

1
如果PROMPT_COMMAND变量中有更多命令(例如,以分隔;),则可能需要在preexec_invoke_exec函数的第二行中使用模式匹配,如下所示:[[ "$PROMPT_COMMAND" =~ "$BASH_COMMAND" ]]。这是因为分别BASH_COMMAND表示每个命令。
jirislav

20

您可以使用trap命令(来自help trap):

如果SIGNAL_SPEC为DEBUG,则在每个简单命令之前执行ARG。

例如,要动态更改终端标题,可以使用:

trap 'echo -e "\e]0;$BASH_COMMAND\007"' DEBUG

这个来源。


1
有趣的是,...在我的旧版Ubuntu服务器上,显示help trap“如果SIGNAL_SPEC是DEBUG,则每个简单命令都会执行ARG ” [强调我的]。
LarsH

1
我将此答案与已接受答案中的一些特殊内容结合使用trap '[ -n "$COMP_LINE" ] && [ "$BASH_COMMAND" != "$PROMPT_COMMAND" ] && date "+%X";echo -e "\e]0;$BASH_COMMAND\007"' DEBUG。这会将命令放在标题中,并在每个命令之前打印当前时间,但是在执行时不这样做$PROMPT_COMMAND
coredumperror

1
@CoreDumpError,由于您已经重构了代码,因此您应否定所有条件:因此第一个条件变为:[ -z "$COMP_LINE" ]
cyrus

@cYrus谢谢!我不知道几乎没有足够的bash编程注意到这一问题。
coredumperror14年

@LarsH:您有哪个版本?我有BASH_VERSION =“ 4.3.11(1)-release”,它说“ ARG 每个简单命令之前执行。”
musiphil 2014年

12

它不是要执行的shell函数,但是我贡献了一个$PS0提示字符串,该提示字符串在每个命令运行之前显示。此处的详细信息:http : //stromberg.dnsalias.org/~strombrg/PS0-prompt/

$PS0包含在bash4.4中,尽管大多数Linux包括4.4会花费一些时间-如果需要,您可以自己构建4.4;在这种情况下,你应该把它放在下/usr/local,将其添加到/etc/shellschsh它。然后注销并重新登录,也许是ssh对自己@localhost或su作为测试首先对自己。


11

我最近不得不为我的一个副项目解决这个确切的问题。我制作了一个相当健壮和有弹性的解决方案,可以模拟zsh的bash preexec和precmd功能。

https://github.com/rcaloras/bash-preexec

它最初是基于Glyph Lefkowitz的解决方案,但是我对此进行了改进并使其更新。乐于帮助或在需要时添加功能。


3

谢谢你的提示!我最终使用了这个:

#created by francois scheurer

#sourced by '~/.bashrc', which is the last runned startup script for bash invocation
#for login interactive, login non-interactive and non-login interactive shells.
#note that a user can easily avoid calling this file by using options like '--norc';
#he also can unset or overwrite variables like 'PROMPT_COMMAND'.
#therefore it is useful for audit but not for security.

#prompt & color
#http://www.pixelbeat.org/docs/terminal_colours/#256
#http://www.frexx.de/xterm-256-notes/
_backnone="\e[00m"
_backblack="\e[40m"
_backblue="\e[44m"
_frontred_b="\e[01;31m"
_frontgreen_b="\e[01;32m"
_frontgrey_b="\e[01;37m"
_frontgrey="\e[00;37m"
_frontblue_b="\e[01;34m"
PS1="\[${_backblue}${_frontgreen_b}\]\u@\h:\[${_backblack}${_frontblue_b}\]\w\\$\[${_backnone}${_frontgreen_b}\] "

#'history' options
declare -rx HISTFILE="$HOME/.bash_history"
chattr +a "$HISTFILE" # set append-only
declare -rx HISTSIZE=500000 #nbr of cmds in memory
declare -rx HISTFILESIZE=500000 #nbr of cmds on file
declare -rx HISTCONTROL="" #does not ignore spaces or duplicates
declare -rx HISTIGNORE="" #does not ignore patterns
declare -rx HISTCMD #history line number
history -r #to reload history from file if a prior HISTSIZE has truncated it
if groups | grep -q root; then declare -x TMOUT=3600; fi #timeout for root's sessions

#enable forward search (ctrl-s)
#http://ruslanspivak.com/2010/11/25/bash-history-incremental-search-forward/
stty -ixon

#history substitution ask for a confirmation
shopt -s histverify

#add timestamps in history - obsoleted with logger/syslog
#http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/#more-130
#declare -rx HISTTIMEFORMAT='%F %T '

#bash audit & traceabilty
#
#
declare -rx AUDIT_LOGINUSER="$(who -mu | awk '{print $1}')"
declare -rx AUDIT_LOGINPID="$(who -mu | awk '{print $6}')"
declare -rx AUDIT_USER="$USER" #defined by pam during su/sudo
declare -rx AUDIT_PID="$$"
declare -rx AUDIT_TTY="$(who -mu | awk '{print $2}')"
declare -rx AUDIT_SSH="$([ -n "$SSH_CONNECTION" ] && echo "$SSH_CONNECTION" | awk '{print $1":"$2"->"$3":"$4}')"
declare -rx AUDIT_STR="[audit $AUDIT_LOGINUSER/$AUDIT_LOGINPID as $AUDIT_USER/$AUDIT_PID on $AUDIT_TTY/$AUDIT_SSH]"
declare -rx AUDIT_SYSLOG="1" #to use a local syslogd
#
#PROMPT_COMMAND solution is working but the syslog message are sent *after* the command execution, 
#this causes 'su' or 'sudo' commands to appear only after logouts, and 'cd' commands to display wrong working directory
#http://jablonskis.org/2011/howto-log-bash-history-to-syslog/
#declare -rx PROMPT_COMMAND='history -a >(tee -a ~/.bash_history | logger -p user.info -t "$AUDIT_STR $PWD")' #avoid subshells here or duplicate execution will occurs!
#
#another solution is to use 'trap' DEBUG, which is executed *before* the command.
#http://superuser.com/questions/175799/does-bash-have-a-hook-that-is-run-before-executing-a-command
#http://www.davidpashley.com/articles/xterm-titles-with-bash.html
#set -o functrace; trap 'echo -ne "===$BASH_COMMAND===${_backvoid}${_frontgrey}\n"' DEBUG
set +o functrace #disable trap DEBUG inherited in functions, command substitutions or subshells, normally the default setting already
#enable extended pattern matching operators
shopt -s extglob
#function audit_DEBUG() {
#  echo -ne "${_backnone}${_frontgrey}"
#  (history -a >(logger -p user.info -t "$AUDIT_STR $PWD" < <(tee -a ~/.bash_history))) && sync && history -c && history -r
#  #http://stackoverflow.com/questions/103944/real-time-history-export-amongst-bash-terminal-windows
#  #'history -c && history -r' force a refresh of the history because 'history -a' was called within a subshell and therefore
#  #the new history commands that are appent to file will keep their "new" status outside of the subshell, causing their logging
#  #to re-occur on every function call...
#  #note that without the subshell, piped bash commands would hang... (it seems that the trap + process substitution interfer with stdin redirection)
#  #and with the subshell
#}
##enable trap DEBUG inherited for all subsequent functions; required to audit commands beginning with the char '(' for a subshell
#set -o functrace #=> problem: completion in commands avoid logging them
function audit_DEBUG() {
    #simplier and quicker version! avoid 'sync' and 'history -r' that are time consuming!
    if [ "$BASH_COMMAND" != "$PROMPT_COMMAND" ] #avoid logging unexecuted commands after Ctrl-C or Empty+Enter
    then
        echo -ne "${_backnone}${_frontgrey}"
        local AUDIT_CMD="$(history 1)" #current history command
        #remove in last history cmd its line number (if any) and send to syslog
        if [ -n "$AUDIT_SYSLOG" ]
        then
            if ! logger -p user.info -t "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])[^0-9])*( )}"
            then
                echo error "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])[^0-9])*( )}"
            fi
        else
            echo $( date +%F_%H:%M:%S ) "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])[^0-9])*( )}" >>/var/log/userlog.info
        fi
    fi
    #echo "===cmd:$BASH_COMMAND/subshell:$BASH_SUBSHELL/fc:$(fc -l -1)/history:$(history 1)/histline:${AUDIT_CMD%%+([^ 0-9])*}===" #for debugging
}
function audit_EXIT() {
    local AUDIT_STATUS="$?"
    if [ -n "$AUDIT_SYSLOG" ]
    then
        logger -p user.info -t "$AUDIT_STR" "#=== bash session ended. ==="
    else
        echo $( date +%F_%H:%M:%S ) "$AUDIT_STR" "#=== bash session ended. ===" >>/var/log/userlog.info
    fi
    exit "$AUDIT_STATUS"
}
#make audit trap functions readonly; disable trap DEBUG inherited (normally the default setting already)
declare -fr +t audit_DEBUG
declare -fr +t audit_EXIT
if [ -n "$AUDIT_SYSLOG" ]
then
    logger -p user.info -t "$AUDIT_STR" "#=== New bash session started. ===" #audit the session openning
else
    echo $( date +%F_%H:%M:%S ) "$AUDIT_STR" "#=== New bash session started. ===" >>/var/log/userlog.info
fi
#when a bash command is executed it launches first the audit_DEBUG(),
#then the trap DEBUG is disabled to avoid a useless rerun of audit_DEBUG() during the execution of pipes-commands;
#at the end, when the prompt is displayed, re-enable the trap DEBUG
declare -rx PROMPT_COMMAND="trap 'audit_DEBUG; trap DEBUG' DEBUG"
declare -rx BASH_COMMAND #current command executed by user or a trap
declare -rx SHELLOPT #shell options, like functrace  
trap audit_EXIT EXIT #audit the session closing

请享用!


我的管道bash命令挂起有问题...我发现了使用subshel​​l的解决方法,但这导致'history -a'无法刷新subshel​​l范围之外的历史记录...最后,解决方案是使用一个函数在执行子Shell之后重新读取历史记录。它可以按我的意愿工作。正如Vaidas在jablonskis.org/2011/howto-log-bash-history-to-syslog所写的那样,与在C中修补bash相比,部署起来更容易(我过去也这样做)。但有一些性能下降,而每一次重读历史文件和做盘“同步” ...
弗朗索瓦scheurer

5
您可能想要修剪该代码;目前,它几乎完全不可读。
l0b0 2012年

3

我编写了一种方法,可以在不使用修补程序或特殊可执行工具的情况下,将所有“ bash”命令/内建命令记录到文本文件或“ syslog”服务器中。

部署非常容易,因为它是一个简单的shellscript,需要在“ bash”初始化时调用一次。

这里查看方法。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.