预计阅读本页时间:-
Process ID Variables and Temporary Files
The only thing new about this script is $$ in the filename expression. This is a special shell variable whose value is the process ID of the current shell.
To see how $$ works, type ps and note the process ID of your shell process (bash). Then type echo "$$"; the shell will respond with that same number. Now type bash to start a subshell, and when you get a prompt, repeat the process. You should see a different number, probably slightly higher than the last one.
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
A related built-in shell variable is ! (i.e., its value is $!), which contains the process ID of the most recently invoked background job. To see how this works, invoke any job in the background and note the process ID printed by the shell next to [1]. Then type echo "$!"; you should see the same number.
To return to our mail example: since all processes on the system must have unique process IDs, $$ is excellent for constructing names of temporary files.
The directory /tmp is conventionally used for temporary files. Many systems also have another directory, /var/tmp, for the same purpose.
Nevertheless, a program should clean up such files before it exits, to avoid taking up unnecessary disk space. We could do this in our code very easily by adding the line rm $msgfile after the code that actually sends the message. But what if the program receives a signal during execution? For example, what if a user changes her mind about sending the message and hits CTRL-C to stop the process? We would need to clean up before exiting. We'll emulate the actual UNIX mail system by saving the message being written in a file called dead.letter in the current directory. We can do this by using trap with a command string that includes an exit command:
trap 'mv $msgfile dead.letter; exit' INT TERM
msgfile=/tmp/msg$$
cat > $msgfile
# send the contents of $msgfile to the specified mail address...
rm $msgfile
When the script receives an INT or TERM signal, it will remove the temp file and then exit. Note that the command string isn't evaluated until it needs to be run, so $msgfile will contain the correct value; that's why we surround the string in single quotes.
But what if the script receives a signal before msgfile is created—unlikely though that may be? Then mv will try to rename a file that doesn't exist. To fix this, we need to test for the existence of the file $msgfile before trying to delete it. The code for this is a bit unwieldy to put in a single command string, so we'll use a function instead:
function cleanup {
if [ -e $msgfile ]; then
mv $msgfile dead.letter
fi
exit
}
trap cleanup INT TERM
msgfile=/tmp/msg$$
cat > $msgfile
# send the contents of $msgfile to the specified mail address...
rm $msgfile