diff --git a/bash-preexec.sh b/bash-preexec.sh index b998944..6c88341 100644 --- a/bash-preexec.sh +++ b/bash-preexec.sh @@ -47,6 +47,12 @@ if [[ -z "${BASH_VERSINFO-}" ]] || (( BASH_VERSINFO[0] < 3 || (BASH_VERSINFO[0] return 1 fi +# We do not enable bash-preexc in non-interactive shells (except in tests). +# `__bp_inside_test` is set in test/*.bats in bash-preexec repository. +if [[ $- != *i* && ! ${__bp_inside_test-} ]]; then + return 0 +fi + # Avoid duplicate inclusion if [[ -n "${bash_preexec_imported:-}" || -n "${__bp_imported:-}" ]]; then return 0 diff --git a/test/README.md b/test/README.md index fd6613c..8836815 100644 --- a/test/README.md +++ b/test/README.md @@ -1,7 +1,7 @@ Testing `bash-preexec` ====================== -**Note on test conditions** +### Note on test conditions When writing test conditions, use `[ ... ]` instead of `[[ ... ]]` since the former are supported by Bats on Bash versions before 4.1. In particular, macOS @@ -20,3 +20,14 @@ References: * [Differences between `[` and `[[`](http://mywiki.wooledge.org/BashFAQ/031) * [Problems with `[[` in Bats](https://github.com/sstephenson/bats/issues/49) * [Using `|| return 1` instead of `|| false`](https://github.com/bats-core/bats-core/commit/e5695a673faad4d4d33446ed5c99d70dbfa6d8be) + + +### Set variable `__bp_inside_test` to test bash-preexec + +By default, bash-preexec is disabled in a non-interactive shell. However, to +test bash-preexec in non-interactive shells, one needs to enable bash-preexec +by setting variable `__bp_inside_test` to a non-empty string. + +```bash +__bp_inside_test=yes +``` diff --git a/test/bash-preexec.bats b/test/bash-preexec.bats index 152d5a6..c1593ea 100644 --- a/test/bash-preexec.bats +++ b/test/bash-preexec.bats @@ -1,5 +1,11 @@ #!/usr/bin/env bats +# This variable tells bash-preexec.sh that it is loaded for testing purposes. +# bash-preexec.sh is intended to be used in interactive shell sessions, so it +# is disabled in non-interactive shells by default. However, it still needs to +# be loaded in non-interactive shells for the Bats tests, +__bp_inside_test=yes + setup() { PROMPT_COMMAND='' # in case the invoking shell has set this history -s fake command # preexec requires there be some history diff --git a/test/include-test.bats b/test/include-test.bats index 36a5f25..7d2bc38 100644 --- a/test/include-test.bats +++ b/test/include-test.bats @@ -1,5 +1,11 @@ #!/usr/bin/env bats +# This variable tells bash-preexec.sh that it is loaded for testing purposes. +# bash-preexec.sh is intended to be used in interactive shell sessions, so it +# is disabled in non-interactive shells by default. However, it still needs to +# be loaded in non-interactive shells for the Bats tests, +__bp_inside_test=yes + @test "should not import if it's already defined" { bash_preexec_imported="defined" source "${BATS_TEST_DIRNAME}/../bash-preexec.sh"