Search code examples
linuxshposixsubshell

Can I avoid this subshell in a POSIX sh script?


I am trying to comprehend how, if even it can be done, can I avoid subshell?

Is this the only way the code can be written or is there another way?

I tried to use braces { ... }, but it won't pass shellcheck and won't run.

is_running_interactively ()
# test if file descriptor 0 = standard input is connected to the terminal
{
    [ -t 0 ]
}

is_tput_available ()
# check if tput coloring is available
{
    command -v tput > /dev/null 2>&1 &&
    tput bold > /dev/null 2>&1 &&
    tput setaf 1 > /dev/null 2>&1
}

some_other_function ()
# so far unfinished function
{
    # is this a subshell? if so, can I avoid it somehow?
    ( is_running_interactively && is_tput_available ) || # <-- HERE
    {
        printf '%b' "${2}"
        return
    }
    ...
}

Solution

  • It is a compound-list, and yes those commands are run in a subshell. To avoid it, use curly braces instead of parentheses:

    { is_running_interactively && is_tput_available; } || ...