0

In a POSIX-compatible shell, is it possible to determine if a script is running inside command substitution?

my-outer $(my-inner)  $(my-other-inner)

For the above example, my-inner and my-other-inner would need to determine if inside command substitution.

  • What are you trying to accomplish? Why would it matter that a script is running inside command substitution? Do you need to differentiate between $(foo) ` foo | bar? between $(foo)` and <(foo)? etc. – Gilles Mar 29 '16 at 22:12
  • I saw it done differently in an other shell (Fish: github.com/fish-shell/fish-shell/blob/master/share/functions/…), and I was curious how it was done in BASH/KSH/MKSH. Right now I don't need it. It's mainly for curiosity and learning purposes. – dgo.a Mar 30 '16 at 7:18
  • I would only need to know if script is in $(foo). Nothing else. – dgo.a Mar 30 '16 at 7:34
1

If I understood well, not realy.

Your question boil down to : am I running foobar from "main" shell or echo $(foobar) (command substitution) ?

foobar may test the following

  • tty (am I under a tty ? )
  • $SHLVL (how many stack of shell ? )

Depending on your need, you may store and compare SHLVL var, this supposed you (your shell) are the one that run the command.

I put quote arroud main, because there is no such thing as main shell, you have loggin shell (with a tty), shell forked from cron, daemons (mails, apache), but no "main" shell.

edit:

as pointed SHLVL might be tricky to use

archemar@home> cat t2.sh
echo "$SHLVL" $1
archemar@home> . ./t2.sh $SHLVL
3 3
archemar@home> ./t2.sh $SHLVL
4 3
archemar@home> ./t2.sh $(./t2.sh)
4 4
archemar@home>
  • $SHLVL won't work. Try echo 'echo "$SHLVL"' > /tmp/test.sh; echo "$(sh /tmp/test.sh)". – cuonglm Mar 29 '16 at 8:24
  • $SHLVL doesn't distinguish between command-substitution and any other kind of sub-shell. – cas Mar 29 '16 at 8:27
1

In zsh, check cmdsubst string is existed inside zsh_eval_context array:

$ echo "$(
  c=cmdsubst
  if (($zsh_eval_context[(Ie)$c])); then
    echo inside cmdsubst
  fi
)"
inside cmdsubst

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.