help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Simple echo is printing the wrong value


From: Eric Blake
Subject: Re: [Help-bash] Simple echo is printing the wrong value
Date: Tue, 03 Apr 2012 20:56:18 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:11.0) Gecko/20120329 Thunderbird/11.0.1

On 04/03/2012 08:46 PM, Bill Gradwohl wrote:
> I can't explain the first output line of every loop, especially when
> compared with the second of every loop.

When in doubt, check for missing quoting.

> #!/bin/bash
> 
> mkdir ./notEmpty
> 
> touch ./notEmpty/*
> touch ./notEmpty/notAsterisk
> ls -al ./notEmpty
> 
> declare loopPass=0
> for x in ./notEmpty/*; do

This expands to:

for x in './notEmpty/*' './notEmpty/notAsterisk'

>    ((++loopPass))
>    echo Length of x=${#x}
>    echo Loop 1 pass ${loopPass} discovered - ${x}

So on the first iteration, $x is the literal value ./notEmpty/*, and
since you forgot to quote the expansion, it is subject to file name
splitting.  In other words, you ended up literally invoking:

echo 'Loop' '1' 'pass' '1' 'discovered' '-' './notEmpty/*'
'./notEmpty/notAsterisk'

whereas if you correctly quoted:

echo "Loop 1 pass ${loopPass} discovered - ${x}"

you would have been invoking:

echo 'Loop 1 pass 1 discovered - ./notEmpty/*'

and getting the output you want.

-- 
Eric Blake   address@hidden    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]