Skip to content

Commit

Permalink
Set command's exit status prior to invoking precmd functions.
Browse files Browse the repository at this point in the history
- In zsh, each precmd function has access to "$?" as if it was executed
  immediately following the command. Simulate this by saving and setting the
  exit status prior to running each precmd function.
  • Loading branch information
rcaloras committed Feb 23, 2015
1 parent bb9a557 commit 417c01b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
13 changes: 12 additions & 1 deletion bash-preexec.sh
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,29 @@ __bp_trim_whitespace() {
#
# It will invoke any functions defined in the precmd_functions array.
__bp_precmd_invoke_cmd() {

# Should be available to each precmd function, should it want it.
local ret_value="$?"

# For every function defined in our function array. Invoke it.
local precmd_function
for precmd_function in ${precmd_functions[@]}; do

# Only execute this function if it actually exists.
if [[ -n $(type -t $precmd_function) ]]; then
__bp_set_ret_value $ret_value
$precmd_function
fi
done
__bp_preexec_interactive_mode="on";
}

# Sets a return value in $?. We may want to get access to the $? variable in our
# precmd functions. This is available for instance in zsh. We can simulate it in bash
# by setting the value here.
__bp_set_ret_value() {
return $1
}

__bp_in_prompt_command() {

Expand Down Expand Up @@ -176,7 +187,7 @@ __bp_preexec_and_precmd_install() {
fi

# Finally install our traps.
PROMPT_COMMAND="${existing_prompt_command} __bp_precmd_invoke_cmd";
PROMPT_COMMAND="__bp_precmd_invoke_cmd; ${existing_prompt_command}"
trap '__bp_preexec_invoke_exec' DEBUG;

# Add two functions to our arrays for convenience
Expand Down
17 changes: 17 additions & 0 deletions test/bash-preexec.bats
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ test_preexec_echo() {
[[ "$output" == "test echo" ]]
}

@test "precmd should set $? to be the previous exit code" {
echo_exit_code() {
echo "$?"
return 0
}
precmd_functions+=(echo_exit_code)

__bp_set_ret_value() {
return 251
}

run '__bp_precmd_invoke_cmd'
[[ $status == 0 ]]
[[ "$output" == "251" ]]
}


@test "preexec should execute a function with the last command in our history" {
preexec_functions+=(test_preexec_echo)
__bp_preexec_interactive_mode="on"
Expand Down

0 comments on commit 417c01b

Please sign in to comment.