Riddle me this Batman! POSIXLY_CORRECT effect on wc
Bob Bell
bobbell at zk3.dec.com
Wed Nov 20 10:01:44 EST 2002
On Wed, Nov 20, 2002 at 09:48:18AM -0500, Steven W. Orr <steveo at syslang.net> wrote:
> I'm trying to get control of some formating that's supposed to be under
> the control of the environment variable POSIXLY_CORRECT. (I can work
> around it but I want to understand this too.)
>
> 663 > wc -l < ~/.bashrc
> 195
> 664 > POSIXLY_CORRECT=1 wc -l < ~/.bashrc
> 195
>
> So far so good. POSIXLY_CORRECT is needed to eliminate the leading spaces.
>
> 665 > foo=$(wc -l < ~/.bashrc)
> 666 > echo $foo
> 195
>
> Huh? How does this happen. I expected four leading spaces!
That's because of how the shell is interpretting what you say on the
command line.
$ foo=$(wc -l < ~/.bashrc)
$ echo $foo #<-- Evaluated as: echo 157
157
$ echo "$foo" #<-- Evaluated as: echo " 157"
157
$
In the first, the first argument is "157", because of the way the shell
parses the command line. In the second, the first argument is
" 157", which is what you expected.
> 671 > cat ~/xxx.sh
> #! /bin/bash
>
> foo=$(wc -l < ~/.bashrc)
> echo "There are $foo lines in bashrc"
> POSIXLY_CORRECT=1 foo=$(wc -l < ~/.bashrc)
> echo "There are $foo lines in bashrc"
>
> 672 > ~/xxx.sh
> There are 195 lines in bashrc
> There are 195 lines in bashrc
> 673 > POSIXLY_CORRECT=1 ~/xxx.sh
> There are 195 lines in bldmaster
> There are 195 lines in bldmaster
> 674 >
>
> I'm totally mystified. Can someone *please* explain this one to me? :-(
Line 5 in xxx.sh is not passing POSIXLY_CORRECT=1 to the sub-shell that
executes the $() contents. Try replacing it with:
foo=$(POSIXLY_CORRECT=1 wc -l < ~/.bashrc)
to get the behavior you expect. Or another way:
export POSIXLY_CORRECT=1
foo=$(wc -l < ~/.bashrc)
--
Bob Bell <bobbell at zk3.dec.com>
-------------------------------------------------------------------------
"It [Linux] will certainly drive us to put new stuff into our products."
-- John Carpenter, Microsoft manager
More information about the gnhlug-discuss
mailing list