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

posix, sh

Solution

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?

Problem

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) ```

Original source

Related problems