OT: bash script - unexpected exit

Frantisek Hanzlik franta at hanzlici.cz
Mon Jan 16 23:05:00 UTC 2012


Andre Speelmans napsal(a):
>> You shouldn't rely on cat or for to read a file line by line, but instead do
>> this:
>>
>> while read line; do
>>   commands
>> done < hosts
> 
> I would pick this form myself, but why should one not rely on cat? It
> seems to me a viable (even if useless use of cat) option.
> Is there something totally wrong with relying on cat to read a file?

main difference is probably in fact that commands in pipe are executed
in subshell - and it means 1) some extra processes, and 2) subshell
environment variables are not passed to parent shell.

Thus script:
#!/bin/bash
echo "1: BASH_SUBSHELL=$BASH_SUBSHELL, PPID=$PPID, BASHPID=$BASHPID, \$\$=$$."
N=0
cat /etc/adjtime | while read line; do
  ((N++))
  echo "  2: BASH_SUBSHELL=$BASH_SUBSHELL, PPID=$PPID, BASHPID=$BASHPID, \$\$=$$, N=$N, line:$line."
done
echo "3: N=$N."

will show:
1: BASH_SUBSHELL=0, PPID=5671, BASHPID=7900, $$=7900.
  2: BASH_SUBSHELL=1, PPID=5671, BASHPID=7902, $$=7900, N=1, line:-0.584209 1326733538 0.000000.
  2: BASH_SUBSHELL=1, PPID=5671, BASHPID=7902, $$=7900, N=2, line:1326733538.
  2: BASH_SUBSHELL=1, PPID=5671, BASHPID=7902, $$=7900, N=3, line:UTC.
3: N=0.

And script:
#!/bin/bash
echo "1: BASH_SUBSHELL=$BASH_SUBSHELL, PPID=$PPID, BASHPID=$BASHPID, \$\$=$$."
N=0
while read line; do
  ((N++))
  echo "  2: BASH_SUBSHELL=$BASH_SUBSHELL, PPID=$PPID, BASHPID=$BASHPID, \$\$=$$, N=$N, line:$line."
done </etc/adjtime
echo "3: N=$N."

will show:
1: BASH_SUBSHELL=0, PPID=5671, BASHPID=7923, $$=7923.
  2: BASH_SUBSHELL=0, PPID=5671, BASHPID=7923, $$=7923, N=1, line:-0.584209 1326733538 0.000000.
  2: BASH_SUBSHELL=0, PPID=5671, BASHPID=7923, $$=7923, N=2, line:1326733538.
  2: BASH_SUBSHELL=0, PPID=5671, BASHPID=7923, $$=7923, N=3, line:UTC.
3: N=3.


More information about the users mailing list