$BASHPID

The following example shows how regular PID (Process ID) $$ fails to get the correct PID for a subshell. While $BASHPID gives the correct PID


unhappy_func(){
  echo "unhappy_func triggered (BASHPID: $BASHPID, PID=$$)"

  return 1
}

happy_func(){
  echo "happy_func triggered (BASHPID: $BASHPID, PID=$$)"

  return 0
}

main() {
  echo "main PID: $$"

  happy_func && (unhappy_func || return 1)

  echo.green "happy finish"
}

main "${@}" || echo.red "Unhappy finish"

The output looks like

main PID: 9200
happy_func triggered (BASHPID: 9200, PID=9200)
unhappy_func triggered (BASHPID: 9201, PID=9200)
happy finish

Also note $BASHPID does not work in zsh.


Backlinks