[Top][All Lists]

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

Re: [Help-bash] declare builtin used with strings

From: Marcio Barbado, Jr.
Subject: Re: [Help-bash] declare builtin used with strings
Date: Wed, 23 Sep 2015 13:35:04 -0300
User-agent: Webmail Locaweb

Hi, sir. Thank you, I'm already adopting your recommendations. Plus your systematic unsets may be perfectly used for separate declaration sections :-)

Em 21.09.2015 09:42, Greg Wooledge escreveu:
On Sun, Sep 20, 2015 at 03:23:45AM -0300, Marcio Barbado, Jr. wrote:
Could you please elaborate or maybe point me to some resource
concerning the reasons why n may "behave in strange and unexpected

I gave examples.  See below.

Also, what about the "let" builtin for integers declarations as in:

let 'n=0'

This is an explicitly invoked math context.  It's perfectly clear just
by looking at the command that you are performing arithmetic.  You
don't have to be aware that six thousand lines ago in a sourced file
someone did a "declare -i n".

I'm not personally fond of the let command because of the extra layer
of quoting it requires (I would prefer ((...)) or n=$((...)) instead),
but it's not bad.

These are the examples I included showing how declare -i changes the
behavior of commands.

$ unset n
$ n=1
$ n+=2
$ echo "$n"

^^ Here we have standard string concatenation, in the absence of declare -i.

$ unset n
$ declare -i n
$ n=1
$ n+=2
$ echo "$n"

^^ Here we have precisely the same commands as before, but now instead of
string concatenation they perform addition.

$ unset n
$ n="hello "
$ n+=world
$ echo "$n"
hello world

^^ Standard string concatenation.

$ unset n
$ delcare -i n
$ n="hello "
$ n+=world
$ echo "$n"

^^ The exact same command as before, but now it performs addition.
"But wait", you might say, "how do you perform addition of `hello '
and `world'?"

In a math context, any non-integer string that can be treated as a
variable name IS treated as a variable name, and the resulting
parameter is expanded.  If that results in an integer, use that.
Otherwise, if it results in another variable name, expand that
recursively, until you get an integer, or a string that cannot be
used as a variable name.

If a variable is unset, treat it as zero. So here we are adding 0 and 0.

$ hello=6 world=8
$ n="hello "
$ echo "$n"
$ n+=world
$ echo "$n"

^^ Here's a similar example, but this time the bash variables `hello'
and `world' have been initialized with integer values.  n is still
declared as an integer, so all of the assignments to n are performed
in math contexts. Bash adds the expansion of hello (6) (also note that
the trailing space is silently dropped) and world (8).

Marcio Barbado, Jr.

reply via email to

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