Home > Enterprise >  expr is not an Linux builtin command,why expr $BASHPID show current shell pid
expr is not an Linux builtin command,why expr $BASHPID show current shell pid

Time:10-31

expr is not an Linux builtin command,why expr $BASHPID show current shell pid?
It's so strange! I think it should output subshell pid.

$ type expr
expr is hashed (/usr/bin/expr)
$ echo $$
49207
$ expr $BASHPID
49207

CodePudding user response:

This is normal and expected: Parameter expansion happens before command execution, so BASHPID tells you the PID of the instance of bash that's determining which arguments to pass to expr, not the PID of expr itself. By the time a fork() takes place, these arguments are already determined.

If you want the PID of expr itself, you can use an explicit subshell to make the fork happen earlier, and then use exec to make expr inherit that subshell's PID:

echo "Parent PID is $$ / $BASHPID"
(printf %s 'expr PID is '; exec expr "$BASHPID")

The ( creates an explicit subshell (instead of the implicit one created during the execution process), so BASHPID then provides its PID; exec causes expr to inherit that PID.

  • Related