What does $$ mean in the shell?

2020-01-23 04:24发布

I once read that one way to obtain a unique filename in a shell for temp files was to use a double dollar sign ($$). This does produce a number that varies from time to time... but if you call it repeatedly, it returns the same number. (The solution is to just use the time.)

I am curious to know what $$ actually is, and why it would be suggested as a way to generate unique filenames.

11条回答
Evening l夕情丶
2楼-- · 2020-01-23 04:39

It's the process ID of the bash process. No concurrent processes will ever have the same PID.

查看更多
劫难
3楼-- · 2020-01-23 04:39

The $$ is the process id of the shell in which your script is running. For more details, see the man page for sh or bash. The man pages can be found be either using a command line "man sh", or by searching the web for "shell manpage"

查看更多
我命由我不由天
4楼-- · 2020-01-23 04:40

$$ is the process ID (PID) in bash. Using $$ is a bad idea, because it will usually create a race condition, and allow your shell-script to be subverted by an attacker. See, for example, all these people who created insecure temporary files and had to issue security advisories.

Instead, use mktemp. The Linux man page for mktemp is excellent. Here's some example code from it:

tempfoo=`basename $0`
TMPFILE=`mktemp -t ${tempfoo}` || exit 1
echo "program output" >> $TMPFILE
查看更多
虎瘦雄心在
5楼-- · 2020-01-23 04:40

Let me second emk's answer -- don't use $$ by itself as a "unique" anything. For files, use mktemp. For other IDs within the same bash script, use "$$$(date +%s%N)" for a reasonably good chance of uniqueness.

 -k
查看更多
成全新的幸福
6楼-- · 2020-01-23 04:41

In Bash $$ is the process ID, as noted in the comments it is not safe to use as a temp filename for a variety of reasons.

For temporary file names, use the mktemp command.

查看更多
在下西门庆
7楼-- · 2020-01-23 04:47

Every process in a UNIX like operating system has a (temporarily) unique identifier, the PID. No two processes running at the same time can have the same PID, and $$ refers to the PID of the bash instance running the script.

This is very much not a unique idenifier in the sense that it will never be reused (indeed, PIDs are reused constantly). What it does give you is a number such that, if another person runs your script, they will get a different identifier whilst yours is still running. Once yours dies, the PID may be recycled and someone else might run your script, get the same PID, and so get the same filename.

As such, it is only really sane to say "$$ gives a filename such that if someone else runs the same script whist my instance is still running, they will get a different name".

查看更多
登录 后发表回答