简体   繁体   中英

How can I differentiate “command substitution” from “subshell” inside a script?

I need to differentiate two cases: ( …subshell… ) vs $( …command substitution… )

I already have the following function which differentiates between being run in either a command substitution or a subshell and being run directly in the script.

#!/bin/bash
set -e

function setMyPid() {
    myPid="$(bash -c 'echo $PPID')"
}

function echoScriptRunWay() {
    local myPid
    setMyPid
    if [[ $myPid == $$ ]]; then
        echo "function run directly in the script"
    else
        echo "function run from subshell or substitution"
    fi
}

echoScriptRunWay
echo "$(echoScriptRunWay)"
( echoScriptRunWay; )

Example output:

function run directly in the script
function run from subshell or substitution
function run from subshell or substitution

Desired output

But I want to update the code so it differentiates between command substitution and subshell. I want it to produce the output:

function run directly in the script
function run from substitution
function run from subshell

PS I need to differentiate these cases because Bash has different behavior for the built-in trap command when run in command substitution and in a subshell.

PPS i care about echoScriptRunWay | cat echoScriptRunWay | cat command also. But it's new question for me which i created here .

I don't think one can reliably test if a command is run inside a command substitution.

You could test if stdout differs from the stdout of the main script, and if it does, boldly infer it might have been redirected. For example

samefd() {
    # Test if the passed file descriptors share the same inode
    perl -MPOSIX -e "exit 1 unless (fstat($1))[1] == (fstat($2))[1]"
}

exec {mainstdout}>&1

whereami() {
    if ((BASHPID == $$))
    then
        echo "In parent shell."
    elif samefd 1 $mainstdout
    then
        echo "In subshell."
    else
        echo "In command substitution (I guess so)."
    fi
}

whereami
(whereami)
echo $(whereami)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM