[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Command substitution optimisation in dot scripts

From: Martijn Dekker
Subject: Command substitution optimisation in dot scripts
Date: Fri, 30 Sep 2016 04:49:33 +0100
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Thunderbird/45.2.0

I detected an oddity (possible bug) in bash: the usual optimisation for
launching external processes in simple command substitutions is turned
off while executing a dot script.

Background: For reasons that would take too much space to explain here,
I need a cross-platform/POSIX way to get the process ID of the current
subshell. I can't use $BASHPID for this as it's only available on newer
bash (not including the default bash on Mac OS X).

As far as I know, the canonical cross-platform way of detecting the PID
of a subshell is:

        my_subshell_pid=$(sh -c 'echo $PPID')

This works fine on every shell, except on bash when a dot script is
being executed.

This can be tested as follows:

        my_subshell_pid=$(sh -c 'echo $PPID') &&
        echo "PID of this subshell is: $my_subshell_pid" &&
        echo "\$BASHPID is: $BASHPID" &&
        trap 'echo "Correctly terminated"; exit 0' TERM &&
        kill -s TERM "$my_subshell_pid"

This works fine on bash if executed normally or in a normal shell script:

$ bash test.sh
PID of this subshell is: 87562
$BASHPID is: 87562
Correctly terminated

But if you source it as a dot script (using '.' or 'source') from the
bash command line or another bash script, the cross-platform method
fails to get the correct subshell PID:

$ source test.sh
PID of this subshell is: 87551
$BASHPID is: 87550
bash: kill: (87551) - No such process

The PID obtained by the cross-platform method is off by one. My educated
(?) guess is that an extra bash subshell process is unnecessarily forked
just to launch the external 'sh' command. If that is the case, then this
adversely affects the performance of dot scripts in bash, which is why I
thought it seems worth reporting here.

Behaviour confirmed on bash-2.05b (Mac), bash-3.2.57 (Mac), bash-4.1.17
(Linux), bash-4.2.53 (Linux), and bash-4.4.0 (Mac).


- M.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]