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.

dgo.a
  • 779
  • 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 'SO- stop being evil' Mar 29 '16 at 22:12
  • I saw it done differently in an other shell (Fish: https://github.com/fish-shell/fish-shell/blob/master/share/functions/psub.fish#L49), 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 07:18
  • I would only need to know if script is in $(foo). Nothing else. – dgo.a Mar 30 '16 at 07:34

2 Answers2

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>
Archemar
  • 31,554
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
cuonglm
  • 153,898