brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: $BASHPID gives the real PID in bash where $$ shows the parent

Bash
~/tips/tip-bash-bashpid-subshell

echo "main: $$ $BASHPID"

Get the PID of the current subshell, where $$ still shows the parent.

$$ looks like the PID of the current shell, but in a subshell it keeps returning the PID of the main script. For lock files and log lines per worker that can be confusing.

$BASHPID always holds the PID of the process you are actually in:

echo "main: $$ $BASHPID"
( echo "subshell: $$ $BASHPID" )
echo x | { echo "pipeline: $BASHPID"; }

In the main script both numbers are the same. Inside the parentheses and in the pipeline, $$ stays the same while $BASHPID changes, because each of those runs in its own process.

That is handy for background workers started with & that each write their own file:

worker() { echo "started" > "/tmp/worker.$BASHPID"; }
worker &
worker &
wait

With $$ both would write to the same file.

$BASHPID arrived in bash 4, so macOS bash 3.2 does not have it. I would also not use it as a secret or for anything long lived, since PIDs get reused once the process ends. For temporary files, mktemp is still the safer way to get a unique name.

Further reading: Bash manual: Bash Variables (BASHPID)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link