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

后端 未结 2 1652
不思量自难忘°
不思量自难忘° 2021-02-20 10:38

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:

<         


        
相关标签:
2条回答
  • 2021-02-20 11:08

    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.

    0 讨论(0)
  • 2021-02-20 11:11

    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?

    0 讨论(0)
提交回复
热议问题