help-bash
[Top][All Lists]
Advanced

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

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


From: Greg Wooledge
Subject: Re: [Help-bash] declare builtin used with strings
Date: Fri, 18 Sep 2015 08:29:59 -0400
User-agent: Mutt/1.4.2.3i

On Thu, Sep 17, 2015 at 01:00:55PM -0300, Marcio Barbado, Jr. wrote:
> is there any sort of risk if, besides using with integers and arrays 
> declarations, I also use the "declare" builtin with strings?
> 
> Something like:
> 
> declare str_mystr

Outside of functions, this doesn't do anything.  Inside a function,
this declares the variable as local to the function.  It is a synonym
for "local str_mystr".

I would strongly recommend AGAINST "integer declarations" in bash.
You mean something like "declare -i n", right?  No sane person does
that.  It makes n behave in strange and unexpected ways, so that
you cannot tell what a command does just by looking at the command.

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

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

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

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

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

In a universe where "declare -i" may exist, you cannot tell by looking
at a bash command whether it will perform string concatenation, addition,
implicit substitution of a word by a number, etc.  This is why no sane
bash programmer will EVER permit declare -i to be used in a script.

Just because a feature exists does not mean you should use it.

The usual way to write bash scripts is to treat everything as a string,
unless the command EXPLICITLY (visibly) uses syntax that creates a math
context.  That way you can always tell what a command is doing.

$ unset n
$ n=6
$ n=$((n+8))     # or ((n+=8)) but the latter is bash-only
$ echo "$n"
14

This way, everything is clear to the reader (which may be you, a year
from now after you've forgotten everything you did).



reply via email to

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