Skip to content

Sourcing bj.sh from bash -c is mistaken for direct execution #24

Description

@memotype

Severity: Medium
Expected real-world likelihood: Medium

Problem

The readable bj.sh is documented as sourceable, but sourcing it from a noninteractive bash -c command triggers the direct-execution footer. The sourced file invokes bj immediately and exits the caller before subsequent commands run.

This calling form is reasonably common in Docker build steps, provisioning systems, and automation wrappers.

Reproduction

bash -c 'source ./bj.sh; printf "reached\n"'
printf 'status=%s\n' "$?"

Actual:

  • reached is not printed;
  • the child shell exits with status 1 because bj was invoked without JSON input.

For comparison, sourcing from a normal script file works, and sourcing bj-1line.sh from bash -c works because the generated form omits the executable footer.

Suspected cause

The footer uses the size of BASH_SOURCE as the execution test:

if ((${#BASH_SOURCE[@]}<=1)) && ! [[ $- =~ i ]]; then
  bj "$@"
  ...
  exit $c
fi

A file sourced directly from bash -c can also have a one-element BASH_SOURCE array.

Possible fixes (suggestions only)

These are possible approaches, not prescribed implementations:

  • Compare the sourced filename with the executing script name, for example using a carefully quoted BASH_SOURCE[0] versus $0 check.
  • Use another direct-execution test that distinguishes bash bj.sh ... and ./bj.sh ... from every sourcing context.
  • Keep the compact function and CLI footer in the same file if that best preserves the current project layout.

Suggested regression coverage

Exercise all of these contexts:

  • direct ./bj.sh DATA QUERY;
  • direct bash bj.sh DATA QUERY;
  • sourcing from a normal script;
  • sourcing from bash -c;
  • sourcing from an interactive shell;
  • correct output and exit status in each supported context.

No global pipefail is needed for these tests.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinginput-transportInput streaming and transport behaviormediumMedium priority

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions