Is is possible in bash - or other sh-derivative shell - to run in the foreground from command-line a list of commands that have their own variable scope (so any values assigned to variables in that scope will not known outside that scope), but also - if spawning a background command - that background command still be a job under the parents shell, i.e. still under the command-line shell's job control? If there are more than 1 way to do this, which way is the most practically short?

I know using parentheses will create new subshell that have its own scope, but any spawned background command will not be under the shell's job control anymore.

  • @ilkkachu, you are right! Actually I was thinking about something and wrote something else. I will fix the question. Mar 4 at 20:51
  • Rereading it again, it was still not correct. Fix it again. Mar 5 at 18:46

1 Answer 1


In zsh, you can use an anonymous function, but you still need to declare variables as local.

For instance:

$ () { local t; for t in 100 200 300; do sleep $t & done; }
[2] 4186
[3] 4187
[4] 4188
$ jobs
[2]    running    sleep $t
[3]  - running    sleep $t
[4]  + running    sleep $t
$ typeset -p t
typeset: no such variable: t

With any shell with support for local scope in functions, you can use a normal function like:

run() { eval "$@"; }


run 'local t; for t in 100 200 300; do sleep "$t" & done'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.