Pumping pads as files into publishing frameworks!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

63 lines
15 KiB

<html>
<head>
<script src="/versions.js"></script>
<link href="../stylesheet.css" rel="stylesheet">
<link href="https://pad.vvvvvvaria.org/p/relearn_bash_preexec" rel="alternate" title="Etherpad" type="text/html">
<link href="relearn_bash_preexec.raw.txt" rel="alternate" title="Plain text" type="text/plain">
<link href="relearn_bash_preexec.raw.html" rel="alternate" title="HTML" type="text/html">
<link href="relearn_bash_preexec.meta.json" rel="alternate" title="Meta data" type="application/json">
<meta charset="utf-8">
<title>relearn_bash_preexec</title>
</head>
<body># __PUBLISH__<br># bash-preexec.sh -- Bash support for ZSH-like 'preexec' and 'precmd' functions.<br># <a href="https://github.com/rcaloras/bash-preexec" rel="noreferrer noopener">https://github.com/rcaloras/bash-preexec</a>
<br>#<br>#<br># 'preexec' functions are executed before each interactive command is<br># executed, with the interactive command as its argument. The 'precmd'<br># function is executed before each prompt is displayed.<br>#<br># Author: Ryan Caloras (ryan@bashhub.com)<br># Forked from Original Author: Glyph Lefkowitz<br>#<br># V0.3.7<br>#<br>
<br># General Usage:<br>#<br>#  1. Source this file at the end of your bash profile so as not to interfere<br>#     with anything else that's using PROMPT_COMMAND.<br>#<br>#  2. Add any precmd or preexec functions by appending them to their arrays:<br>#       e.g.<br>#       precmd_functions+=(my_precmd_function)<br>#       precmd_functions+=(some_other_precmd_function)<br>#<br>#       preexec_functions+=(my_preexec_function)<br>#<br>#  3. Consider changing anything using the DEBUG trap or PROMPT_COMMAND<br>#     to use preexec and precmd instead. Preexisting usages will be<br>#     preserved, but doing so manually may be less surprising.<br>#<br>#  Note: This module requires two Bash features which you must not otherwise be<br>#  using: the "DEBUG" trap, and the "PROMPT_COMMAND" variable. If you override<br>#  either of these after bash-preexec has been installed it will most likely break.<br>
<br># Avoid duplicate inclusion<br>if [[ "${__bp_imported:-}" == "defined" ]]; then<br>    return 0<br>fi<br>__bp_imported="defined"<br>
<br># Should be available to each precmd and preexec<br># functions, should they want it. $? and $_ are available as $? and $_, but<br># $PIPESTATUS is available only in a copy, $BP_PIPESTATUS.<br># TODO: Figure out how to restore PIPESTATUS before each precmd or preexec<br># function.<br>__bp_last_ret_value="$?"<br>BP_PIPESTATUS=("${PIPESTATUS[@]}")<br>__bp_last_argument_prev_command="$_"<br>
<br>__bp_inside_precmd=0<br>__bp_inside_preexec=0<br>
<br># Fails if any of the given variables are readonly<br># Reference <a href="https://stackoverflow.com/a/4441178" rel="noreferrer noopener">https://stackoverflow.com/a/4441178</a>
<br>__bp_require_not_readonly() {<br>  for var; do<br>    if ! ( unset "$var" 2&gt; /dev/null ); then<br>      echo "bash-preexec requires write access to ${var}" &gt;&amp;2<br>      return 1<br>    fi<br>  done<br>}<br>
<br># Remove ignorespace and or replace ignoreboth from HISTCONTROL<br># so we can accurately invoke preexec with a command from our<br># history even if it starts with a space.<br>__bp_adjust_histcontrol() {<br>    local histcontrol<br>    histcontrol="${HISTCONTROL//ignorespace}"<br>    # Replace ignoreboth with ignoredups<br>    if [[ "$histcontrol" == *"ignoreboth"* ]]; then<br>        histcontrol="ignoredups:${histcontrol//ignoreboth}"<br>    fi;<br>    export HISTCONTROL="$histcontrol"<br>}<br>
<br># This variable describes whether we are currently in "interactive mode";<br># i.e. whether this shell has just executed a prompt and is waiting for user<br># input.  It documents whether the current command invoked by the trace hook is<br># run interactively by the user; it's set immediately after the prompt hook,<br># and unset as soon as the trace hook is run.<br>__bp_preexec_interactive_mode=""<br>
<br>__bp_trim_whitespace() {<br>    local var=$@<br>    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters<br>    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters<br>    echo -n "$var"<br>}<br>
<br># This function is installed as part of the PROMPT_COMMAND;<br># It sets a variable to indicate that the prompt was just displayed,<br># to allow the DEBUG trap to know that the next command is likely interactive.<br>__bp_interactive_mode() {<br>    __bp_preexec_interactive_mode="on";<br>}<br>
<br>
<br># This function is installed as part of the PROMPT_COMMAND.<br># It will invoke any functions defined in the precmd_functions array.<br>__bp_precmd_invoke_cmd() {<br>    # Save the returned value from our last command, and from each process in<br>    # its pipeline. Note: this MUST be the first thing done in this function.<br>    __bp_last_ret_value="$?" BP_PIPESTATUS=("${PIPESTATUS[@]}")<br>
<br>    # Don't invoke precmds if we are inside an execution of an "original<br>    # prompt command" by another precmd execution loop. This avoids infinite<br>    # recursion.<br>    if (( __bp_inside_precmd &gt; 0 )); then<br>      return<br>    fi<br>    local __bp_inside_precmd=1<br>
<br>    # Invoke every function defined in our function array.<br>    local precmd_function<br>    for precmd_function in "${precmd_functions[@]}"; do<br>
<br>        # Only execute this function if it actually exists.<br>        # Test existence of functions with: declare -[Ff]<br>        if type -t "$precmd_function" 1&gt;/dev/null; then<br>            __bp_set_ret_value "$__bp_last_ret_value" "$__bp_last_argument_prev_command"<br>            # Quote our function invocation to prevent issues with IFS<br>            "$precmd_function"<br>        fi<br>    done<br>}<br>
<br># Sets a return value in $?. We may want to get access to the $? variable in our<br># precmd functions. This is available for instance in zsh. We can simulate it in bash<br># by setting the value here.<br>__bp_set_ret_value() {<br>    return ${1:-}<br>}<br>
<br>__bp_in_prompt_command() {<br>
<br>    local prompt_command_array<br>    IFS=';' read -ra prompt_command_array &lt;&lt;&lt; "$PROMPT_COMMAND"<br>
<br>    local trimmed_arg<br>    trimmed_arg=$(__bp_trim_whitespace "${1:-}")<br>
<br>    local command<br>    for command in "${prompt_command_array[@]:-}"; do<br>        local trimmed_command<br>        trimmed_command=$(__bp_trim_whitespace "$command")<br>        # Only execute each function if it actually exists.<br>        if [[ "$trimmed_command" == "$trimmed_arg" ]]; then<br>            return 0<br>        fi<br>    done<br>
<br>    return 1<br>}<br>
<br># This function is installed as the DEBUG trap.  It is invoked before each<br># interactive prompt display.  Its purpose is to inspect the current<br># environment to attempt to detect if the current command is being invoked<br># interactively, and invoke 'preexec' if so.<br>__bp_preexec_invoke_exec() {<br>    # Save the contents of $_ so that it can be restored later on.<br>    # <a href="https://stackoverflow.com/questions/40944532/bash-preserve-in-a-debug-trap#40944702" rel="noreferrer noopener">https://stackoverflow.com/questions/40944532/bash-preserve-in-a-debug-trap#40944702</a>
<br>    __bp_last_argument_prev_command="${1:-}"<br>    # Don't invoke preexecs if we are inside of another preexec.<br>    if (( __bp_inside_preexec &gt; 0 )); then<br>      return<br>    fi<br>    local __bp_inside_preexec=1<br>
<br>    # Checks if the file descriptor is not standard out (i.e. '1')<br>    # __bp_delay_install checks if we're in test. Needed for bats to run.<br>    # Prevents preexec from being invoked for functions in PS1<br>    if [[ ! -t 1 &amp;&amp; -z "${__bp_delay_install:-}" ]]; then<br>        return<br>    fi<br>
<br>    if [[ -n "${COMP_LINE:-}" ]]; then<br>        # We're in the middle of a completer. This obviously can't be<br>        # an interactively issued command.<br>        return<br>    fi<br>    if [[ -z "${__bp_preexec_interactive_mode:-}" ]]; then<br>        # We're doing something related to displaying the prompt.  Let the<br>        # prompt set the title instead of me.<br>        return<br>    else<br>        # If we're in a subshell, then the prompt won't be re-displayed to put<br>        # us back into interactive mode, so let's not set the variable back.<br>        # In other words, if you have a subshell like<br>        #   (sleep 1; sleep 2)<br>        # You want to see the 'sleep 2' as a set_command_title as well.<br>        if [[ 0 -eq "${BASH_SUBSHELL:-}" ]]; then<br>            __bp_preexec_interactive_mode=""<br>        fi<br>    fi<br>
<br>    if  __bp_in_prompt_command "${BASH_COMMAND:-}"; then<br>        # If we're executing something inside our prompt_command then we don't<br>        # want to call preexec. Bash prior to 3.1 can't detect this at all :/<br>        __bp_preexec_interactive_mode=""<br>        return<br>    fi<br>
<br>    local this_command<br>    this_command=$(<br>        export LC_ALL=C<br>        HISTTIMEFORMAT= builtin history 1 | sed '1 s/^ *[0-9][0-9]*[* ] //'<br>    )<br>
<br>    # Sanity check to make sure we have something to invoke our function with.<br>    if [[ -z "$this_command" ]]; then<br>        return<br>    fi<br>
<br>    # If none of the previous checks have returned out of this function, then<br>    # the command is in fact interactive and we should invoke the user's<br>    # preexec functions.<br>
<br>    # Invoke every function defined in our function array.<br>    local preexec_function<br>    local preexec_function_ret_value<br>    local preexec_ret_value=0<br>    for preexec_function in "${preexec_functions[@]:-}"; do<br>
<br>        # Only execute each function if it actually exists.<br>        # Test existence of function with: declare -[fF]<br>        if type -t "$preexec_function" 1&gt;/dev/null; then<br>            __bp_set_ret_value ${__bp_last_ret_value:-}<br>            # Quote our function invocation to prevent issues with IFS<br>            "$preexec_function" "$this_command"<br>            preexec_function_ret_value="$?"<br>            if [[ "$preexec_function_ret_value" != 0 ]]; then<br>                preexec_ret_value="$preexec_function_ret_value"<br>            fi<br>        fi<br>    done<br>
<br>    # Restore the last argument of the last executed command, and set the return<br>    # value of the DEBUG trap to be the return code of the last preexec function<br>    # to return an error.<br>    # If `extdebug` is enabled a non-zero return value from any preexec function<br>    # will cause the user's command not to execute.<br>    # Run `shopt -s extdebug` to enable<br>    __bp_set_ret_value "$preexec_ret_value" "$__bp_last_argument_prev_command"<br>}<br>
<br>__bp_install() {<br>    # Exit if we already have this installed.<br>    if [[ "${PROMPT_COMMAND:-}" == *"__bp_precmd_invoke_cmd"* ]]; then<br>        return 1;<br>    fi<br>
<br>    trap '__bp_preexec_invoke_exec "$_"' DEBUG<br>
<br>    # Preserve any prior DEBUG trap as a preexec function<br>    local prior_trap=$(sed "s/[^']*'\(.*\)'[^']*/\1/" &lt;&lt;&lt;"${__bp_trap_string:-}")<br>    unset __bp_trap_string<br>    if [[ -n "$prior_trap" ]]; then<br>        eval '__bp_original_debug_trap() {<br>          '"$prior_trap"'<br>        }'<br>        preexec_functions+=(__bp_original_debug_trap)<br>    fi<br>
<br>    # Adjust our HISTCONTROL Variable if needed.<br>    __bp_adjust_histcontrol<br>
<br>
<br>    # Issue #25. Setting debug trap for subshells causes sessions to exit for<br>    # backgrounded subshell commands (e.g. (pwd)&amp; ). Believe this is a bug in Bash.<br>    #<br>    # Disabling this by default. It can be enabled by setting this variable.<br>    if [[ -n "${__bp_enable_subshells:-}" ]]; then<br>
<br>        # Set so debug trap will work be invoked in subshells.<br>        set -o functrace &gt; /dev/null 2&gt;&amp;1<br>        shopt -s extdebug &gt; /dev/null 2&gt;&amp;1<br>    fi;<br>
<br>    # Install our hooks in PROMPT_COMMAND to allow our trap to know when we've<br>    # actually entered something.<br>    PROMPT_COMMAND="__bp_precmd_invoke_cmd; __bp_interactive_mode"<br>
<br>    # Add two functions to our arrays for convenience<br>    # of definition.<br>    precmd_functions+=(precmd)<br>    preexec_functions+=(preexec)<br>
<br>    # Since this function is invoked via PROMPT_COMMAND, re-execute PC now that it's properly set<br>    eval "$PROMPT_COMMAND"<br>}<br>
<br># Sets our trap and __bp_install as part of our PROMPT_COMMAND to install<br># after our session has started. This allows bash-preexec to be included<br># at any point in our bash profile. Ideally we could set our trap inside<br># __bp_install, but if a trap already exists it'll only set locally to<br># the function.<br>__bp_install_after_session_init() {<br>
<br>    # Make sure this is bash that's running this and return otherwise.<br>    if [[ -z "${BASH_VERSION:-}" ]]; then<br>        return 1;<br>    fi<br>
<br>    # bash-preexec needs to modify these variables in order to work correctly<br>    # if it can't, just stop the installation<br>    __bp_require_not_readonly PROMPT_COMMAND HISTCONTROL HISTTIMEFORMAT || return<br>
<br>    # If there's an existing PROMPT_COMMAND capture it and convert it into a function<br>    # So it is preserved and invoked during precmd.<br>    if [[ -n "$PROMPT_COMMAND" ]]; then<br>      eval '__bp_original_prompt_command() {<br>        '"$PROMPT_COMMAND"'<br>      }'<br>      precmd_functions+=(__bp_original_prompt_command)<br>    fi<br>
<br>    # Installation is finalized in PROMPT_COMMAND, which allows us to override the DEBUG<br>    # trap. __bp_install sets PROMPT_COMMAND to its final value, so these are only<br>    # invoked once.<br>    # It's necessary to clear any existing DEBUG trap in order to set it from the install function.<br>    # Using \n as it's the most universal delimiter of bash commands<br>    PROMPT_COMMAND=$'\n__bp_trap_string="$(trap -p DEBUG)"\ntrap DEBUG\n__bp_install\n'<br>}<br>
<br># Run our install so long as we're not delaying it.<br>if [[ -z "$__bp_delay_install" ]]; then<br>    __bp_install_after_session_init<br>fi;<br>
</body>
</html>