0

If I define a bash function like this

test1 () {
 (
 touch /tmp/test1
 rm /tmp/test1
 read -rp "Enter anything: " anything
 echo "Anything: ${anything}"
 )
}

and set this option and trap

trap 'echo trapped' DEBUG;
shopt -s extdebug

and then execute it from an interactive bash session the read statement stops the job.

$ test1 () {
 (
 touch /tmp/test1
 rm /tmp/test1
 read -rp "Enter anything: " anything
 echo "Anything: ${anything}"
 )
}
$ test1
Enter anything:
[1]+ Stopped ( touch /tmp/test1; rm /tmp/test1; read -p "Enter anything: " anything; echo "Anything: ${anything}" )
$ fg 1
( touch /tmp/test1; rm /tmp/test1; read -p "Enter anything: " anything; echo "Anything: ${anything}" )
something
Anything: something

If I only have one command before the read then the function executes as expected.

This is a minimum example to reproduce the issue. I have work arounds but I'm trying to understand this behavior. Bash version is 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

John Bollinger
192k11 gold badges103 silver badges209 bronze badges
asked Jan 24, 2025 at 13:48
27
  • 2
    I do not reproduce the issue with the code presented, though I am running it in an earlier Bash. And I don't expect Bash or a POSIX shell to run any part of that command in the background, which your output appears to show is happening. Commented Jan 24, 2025 at 14:46
  • To the extent that the code presented is sufficient for you to reproduce the issue in your Bash, I would be inclined to guess that it is related to putting all the work inside a subshell. I don't see what purpose is served by doing so in the function presented, that could not be better addressed by other means. Commented Jan 24, 2025 at 14:50
  • 3
    To keep variable local use local within a function: local anything Commented Jan 24, 2025 at 15:53
  • 1
    A subshell is a pretty heavy tool for namespacing. Declaring variables local is the "other means" I had in mind for that particular objective. Subshells do provide isolation for other aspects of the execution environment, so there might still be a reasonable use case there, but it depends on what exactly you need to isolate. Commented Jan 24, 2025 at 16:39
  • 2
    You can use local -x to create a local variable that is exported. Commented Jan 24, 2025 at 17:45

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.