[Gllug] Bourne shell programming
Mike Brodbelt
mike at coruscant.demon.co.uk
Sun Nov 19 14:22:06 UTC 2006
Tethys wrote:
>> Now variables I set inside the loop vanish, as the pipe causes a
>> subshell to be spawned, so I can't set variables in the body of my
>> loop that are visible to the rest of the script.
>
> Yep. It's the single most annoying feature of shell scripting[1].
Yes, after spending far too long fighting to achieve a simple result, I
think I'd go with that view :-)
> If you're using bash or zsh, you can get around it by using process
> substitution:
>
> while read x
> do
> some stuff
> done < <(grep root /etc/passwd | awk -F: '{print $1,$2,$3}')
Clever, but ewwwww :-).
> If you're using a traditional Bourne or Korn[2] shell
Yep - it's in a shell script on a Solaris box, so it's a hoary old
Bourne shell.
<snip>
> It's crude and ugly, but it works. You can, of course, use multiple
> temporary files if you have multiple values to return (which is even
> more ugly, but easier than trying to multiplex multiple values into
> a single file).
I ended up last night using temp files, but I've found a route today
which I'm happier with for this particular script, which was to do it like:-
output=`grep root /etc/passwd | awk -F: '{print $1,$2,$3}'`
for line in $output
do
stuff
done
which just provides a different route to get information back from the
subshell. Thanks for the help - much appreciated. I don't do a lot of
shell, and it always seems painful :-)
Mike
--
Gllug mailing list - Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug
More information about the GLLUG
mailing list