pid=`cat $pidfile` or read pid <$pidfile?

2019-04-24 08:04发布

问题:

I read a lot of init.d scripts and:

pid=`cat $pidfile`

lines make me sad. I don't understand why people doesn't use:

read pid <$pidfile

Last sample uses POSIX compliant syntax and doesn't do fork/exec to run external process (cat).

Last solution also allow skipping content after first newline.

Are there any traps with read command (despite that it perform splitting into fields)?

UPDATE. Some peole use non-portable extension for shell like:

How to get variable from text file into Bash variable

pid=$(<$pidfile)

回答1:

The read pid < file way is the Best Practice for the reason you stated: much cheaper than a fork/exec of cat.

As for why so many scripts do this the expensive way, I can only speculate. Probably cut'n'paste from other people's scripts, together with lack of knowledge of shell features, together with blazingly fast CPUs. Who reads man pages when there's Stack Overflow? :-) Especially the shell man page is a hard-to-read reference manual for novices due to all the terminology introduced.

Who said Useless Use of Cat was a privilege for pipes?



回答2:

Looking at computer programming languages offer some insight into why pid initialization by way of cat command might be preferable to using read command to set pid.

Since this question is regarding the POSIX shell, considering the timeline of such a development along with other languages might also help.

Consider C++ as an example. Although C++ is nothing like shell, the underlying mechanism to achieve portability (which is the goal of POSIX) places highly portable languages like C++ in same genre as scripting languages like POSIX shell.

Remembering that aside from the syntax of the language and the cost incurred by executing a certain format, in order for a language to attain a degree of freedom in portability, the language must be able to interface with the hardware performing the command.

With this much said, C++ offers a glimpse of the real cost of using read command to read from the pidfile instead of simply setting pid variable line-by-line using the cat command's output.

In C++, one of the many ways to read user input is to use std::cin. In order for this process to occur, the language's compiler has to read into (e.g. >>) the user input at run time. By comparison, to perform an output the compiler merely reads from (e.g. <<) either the string or the function call. As mentioned in various C++ texts, std::cin is not an inexpensive task.

Keep in mind that shell is a command-line interpreter, not a statically typed compiler.

With this clue, one could conclude that based on the issues surrounding hardware compatibility, setting pid by output is preferable to reading from a pidfile by invoking read command.



标签: posix sh