Skip to content

Commit e5ebc33

Browse files
dseomnrcaloras
authored andcommitted
Save $PIPESTATUS for precmd and preexec functions to use. (#85)
Unfortunately, I couldn't figure out how to restore it for each function, so I just made a copy in $BP_PIPESTATUS for those functions to use. For documentation of PIPESTATUS, see https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html#index-PIPESTATUS Closes #81.
1 parent 533b05e commit e5ebc33

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

bash-preexec.sh

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,12 @@ fi
3939
__bp_imported="defined"
4040

4141
# Should be available to each precmd and preexec
42-
# functions, should they want it.
42+
# functions, should they want it. $? and $_ are available as $? and $_, but
43+
# $PIPESTATUS is available only in a copy, $BP_PIPESTATUS.
44+
# TODO: Figure out how to restore PIPESTATUS before each precmd or preexec
45+
# function.
4346
__bp_last_ret_value="$?"
47+
BP_PIPESTATUS=("${PIPESTATUS[@]}")
4448
__bp_last_argument_prev_command="$_"
4549

4650
__bp_inside_precmd=0
@@ -95,9 +99,9 @@ __bp_interactive_mode() {
9599
# This function is installed as part of the PROMPT_COMMAND.
96100
# It will invoke any functions defined in the precmd_functions array.
97101
__bp_precmd_invoke_cmd() {
98-
# Save the returned value from our last command. Note: this MUST be the
99-
# first thing done in this function.
100-
__bp_last_ret_value="$?"
102+
# Save the returned value from our last command, and from each process in
103+
# its pipeline. Note: this MUST be the first thing done in this function.
104+
__bp_last_ret_value="$?" BP_PIPESTATUS=("${PIPESTATUS[@]}")
101105

102106
# Don't invoke precmds if we are inside an execution of an "original
103107
# prompt command" by another precmd execution loop. This avoids infinite

test/bash-preexec.bats

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,22 @@ test_preexec_echo() {
109109
[[ "$output" == "251" ]]
110110
}
111111

112+
@test "precmd should set \$BP_PIPESTATUS to the previous \$PIPESTATUS" {
113+
echo_pipestatus() {
114+
echo "${BP_PIPESTATUS[*]}"
115+
}
116+
# Helper function is necessary because Bats' run doesn't preserve $PIPESTATUS
117+
set_pipestatus_and_run_precmd() {
118+
false | true
119+
__bp_precmd_invoke_cmd
120+
}
121+
122+
precmd_functions+=(echo_pipestatus)
123+
run 'set_pipestatus_and_run_precmd'
124+
[[ $status == 0 ]]
125+
[[ "$output" == "1 0" ]]
126+
}
127+
112128
@test "precmd should set \$_ to be the previous last arg" {
113129
echo_last_arg() {
114130
echo "$_"

0 commit comments

Comments
 (0)