bug-bash
[Top][All Lists]
Advanced

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

Re: Preventing Bash Variable Confusion


From: Greg Wooledge
Subject: Re: Preventing Bash Variable Confusion
Date: Wed, 29 Jan 2020 09:23:05 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Wed, Jan 29, 2020 at 12:57:41PM +0700, Robert Elz wrote:
> Incidentally, since sh (all implementations, including bash) has a global
> variable namespace, the biggest source of variable name conflicts is
> usually with other sh scripts (functions, startup files,
> environment variables...) that are incorporated into your script.   This one
> is hard to deal with, as anything at all is possible, depending upon
> the origin of such a thing - and while re-using such a name is unlikely to
> harm your script (providing you always initialize vars, and never just assume
> they will be null valued/unset before their first assignment), but you can
> break other functionality by stealing one of its variables.
> 
> Note that no convention you adopt can avoid this problem, as the other
> function might have adopted the exact same convention.

The primary convention to be observed and followed is:

 * A variable name in ALL_CAPS is either an environment variable, or an
   internal shell variable.

As long as you use at least one lowercase letter in your variable name,
you are guaranteed not to conflict with any internal shell variables.
You're also virtually guaranteed not to conflict with any environment
variables -- the only exception to this would be if someone else has
violated the convention.

As far as functions go, bash allows you to define local variables within
a function.  This avoids namespace collisions as long as you're within
that function.  Obviously, sh doesn't have this feature, but then again,
sh is primitive trash by today's standards, and if you're forced to use
it, you simply have to endure the agony.

Since the Subject: of this thread includes the word "Bash", it seems
likely that the OP is not concerned with portable-sh issues at the
moment.



reply via email to

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