Why does echo $$ return a number? [duplicate]

落爺英雄遲暮 提交于 2019-12-25 04:23:06

问题


Why do I get a number when doing that :

echo $$

which returns

489

If I open a new terminal it returns another number. It seems it's related to the pid of the terminal session, but why ?


回答1:


$$ means your current PID.

As seen in Bash Reference Manual - 3.4.2 Special Parameters:

$

Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the invoking shell, not the subshell.

You can test it by doing ps -ef | grep 489, and it will show the process in which you are logged in.

For example in my case:

$ echo $$
3470

$ ps -ef | grep 3470
1000      3470  3469  0 10:59 pts/3    00:00:00 -bash    <---- this process
1000      8151  3470  0 15:37 pts/3    00:00:00 ps -ef
1000      8152  3470  0 15:37 pts/3    00:00:00 grep --color=auto 3470



回答2:


Because that's how it is defined. $$ is a special shell variable (like e.g. $!, $_, $@, $1, ...) referring to the PID of the invoked shell.




回答3:


You will find an excellent explanation in this post.

$$ pid of the current shell (not subshell)



来源:https://stackoverflow.com/questions/22457166/why-does-echo-return-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!