- To: slug <slug@xxxxxxxxxxx>
- Subject: Re: [SLUG] shell scripting help
- From: Gonzalo Servat <gservat@xxxxxxxxx>
- Date: Sat, 19 Sep 2009 00:41:09 +1000
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=domainkey-signature:mime-version:received:in-reply-to:references :date:message-id:subject:from:to:content-type; bh=iaPJqiLlHwBnIDBitLkYd4eiB3gFqAxkjyCj0ZLPAb0=; b=YYKrwvWfT4BvVmPDvrhYzvnlVdO0aSU9CughtoohT7U1x73u/zHwc1DFNt3XQHMjM3 kAohbiBe55jJF0IhxUQonpIoFJugp5wOLsLqWgPMhqSeNXhhw0peqO0WkA8zZUVYYJnC YTYsIDsShmcUMDRvsUFO3nhaON42KkM1He4Uk=
- Domainkey-signature: a=rsa-sha1; c=nofws; d=gmail.com; s=gamma; h=mime-version:in-reply-to:references:date:message-id:subject:from:to :content-type; b=a/DduUrN+zrrEd0LWB6fIDUYtzs7bWaLDhrrXxRZNehEo0/O+rLbZan4SYOjvsFvcG eiwBGaaORpGl8F16kdwVQaOyKUh/pSlShcL1PmKwGNcDfq+xIrXClufcAgQ2Lmlb5pMs v+wrADQKLtYEN6lsscmbN6j6MC8BnIPX81GNE=
On Fri, Sep 18, 2009 at 11:42 PM, Daniel Bush <dlb.id.au@xxxxxxxxx> wrote:
> Hi,
> Writing a little utility to help me on something but having trouble.
> Why does f stay blank?
>
> danb@lin4:test$ echo "foo|bar" | awk 'BEGIN{RS="|"}{ print $1 }' | while
> read s; do echo $s; f=$s; done; echo "'$f'"
> foo
> bar
> ''
As I understand it (only just looked this up), it's to do with the
fact that you're subshelling[1] by piping output to the while loop,
which makes the $f variable only visible in the subshell and not the
parent process. After the while loop ends, it returns control to the
parent process where the $f variable can't be seen. This works:
while read s; do
echo $s;
f=$s;
done < <(echo "foo|bar" | awk 'BEGIN{RS="|"}{ print $1 }')
echo "'$f'"
HTH,
- Gonzalo
[1] http://fvue.nl/wiki/Bash:_Piped_`while-read'_loop_starts_subshell