help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] When are double quotes necessary?


From: Eric Blake
Subject: Re: [Help-bash] When are double quotes necessary?
Date: Sat, 14 Sep 2013 07:02:23 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130805 Thunderbird/17.0.8

On 09/14/2013 06:52 AM, adrelanos wrote:
> Just an example.
> 
> temp="/etc/"
> file="name"
> 
> a)
> config_file="$temp/$file"
> 
> b)
> config_file=""$temp"/"$file""
> 
> c)
> config_file=$temp/$file

a, b, and c are identical.

> 
> d)
> i=0
> 
> e)
> i="0"

d and e are identical.

> 
> First, a) vs b). I like the look and feel of a) more. Is b) necessary
> and/or advised in this case?
> 
> Actually, c) should work as well, but it is not advised, because if
> temp="/etc/ ", this could be end in a disaster just of because an
> extra space.

No, they are identical _in this context_, even if $temp expands to
something that contains space.  Word splitting is NOT performed in
assignment context.  Quoting has two purposes: to suppress word
splitting, and to delineate words.  In your case, no word delineation is
needed ($temp/$file is already a single word), and since there is no
word splitting in assignment context, quoting adds nothing other than
consistency.  But if you were NOT doing an assignment (such as:
echo "$temp/$file"
or other non-assignment context), where word splitting is performed,
then quotes are essential.

Some people swear by quoting all variables all the time on the grounds
of consistency being easier to remember, but I personally like omitting
quotes unless they make a difference.

> 
> For trivial cases, such as d) vs e), are quotes still recommended?

Style is such a personal thing.  Some people swear by consistently using
quotes everywhere possible, while I personally like omitting them if
they make no difference.  But bash doesn't care either way.

-- 
Eric Blake   eblake redhat com    +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]