打印 PID 到文件

Print PID to file

我正在尝试使 bash 脚本在终端中成为 运行,该终端将自己的 PID 打印到 .txt 文件中脚本的开头。

我知道您可以通过输入 $$ 获得响应式终端的 PID,但如果我这样做,PID 会自动执行,因此输出不是 PID,而是 bash:PIDNUMVALUE: command not found,如果我将 $$ 的输出打印到 .txt 文件中,输出将不是 PID,而是 bash:PIDNUMVALUE: command not found 而我只想将 PID 打印在 txt 文件中。

我该怎么做?

试试这个:

echo $$ > my.pid

或者使用 $BASHPID 来提高脚本的可读性 IMO,但请记住两者之间的一些细微差别:

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized.

查看 the Bash manual 了解更多信息。