[plug] Bash "Processing" Script
Bernard Blackham
bernard at blackham.com.au
Sat Jun 12 01:30:21 WST 2004
On Sat, Jun 12, 2004 at 12:55:34AM +0800, Bernd Felsche wrote:
> Piping or backgrounding a flow contruct creates a sub-process.
>
> This creates inconvenience when doing something like:
>
> OIFS="$IFS"
> IFS=":"
> cat /etc/passwd |
> while read uname pwd uid gid gcos home shell ; do
> if [ $uid -eq 0 ] ; then
> root=$uname
> break
> fi
> done
> IFS="$OIFS"
> echo $root
>
> Variables set in the other process will not be available in the
> parent. Note that I've set the shell's input field separator to
> the colon which separates fields in the /etc/passwd file.
For this particular instance, you can rearrange it to read:
while read uname pwd uid gid gcos home shell ; do
if [ $uid -eq 0 ] ; then
root=$uname
break
fi
done < /etc/passwd
But agreed - there are situations where it's not that simple. I've
yet to come up with an elegant solution for a script like:
(
echo -n "Backup starting at "
date
<other random commands>
rsync .....
) | tee $LOGFILE
I want this to return the exit status of the rsync command, but
instead I get the exit status of tee. I could redirect it all to a
logfile and tail the logfile, but I'd rather not :)
> Similarly, one could use the 'set' command to set up a new "argument
> list" to the shell program. e.g.
>
> set -- `IFS=":" ; cat /etc/passwd |
> while read uname pwd uid gid gcos home shell ; do
> [ $uid -eq 0 ] && echo $uname
> done`
> echo $*
Never knew about that one! Cool :)
> kill is also "cheap" as it's a builtin in most modern shells;
> whereas ps is usually an external command. When I were a lad, kill
> wasn't builtin and if you ran out of process table entries, you
> couldn't kill anything. You had to sit tight and wait for something
> to finish or crash the system.
Heh, there's a catch-22. Hurrah for process limits (but who actually
considers using one until it's too late? :)
Bernard.
--
Bernard Blackham <bernard at blackham dot com dot au>
More information about the plug
mailing list