help-bash
[Top][All Lists]
Advanced

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

Re: Why is -- in the output of declare -p x?


From: Kerin Millar
Subject: Re: Why is -- in the output of declare -p x?
Date: Thu, 26 Jan 2023 16:27:19 +0000

On Thu, 26 Jan 2023 09:23:35 -0600
Peng Yu <pengyu.ut@gmail.com> wrote:

> "Consider the ramifications of the latter paragraph of Koichi's
> response. As was stated, it is potentially useful for a program that
> processes the output of `declare -p` to be able to assume that the
> second word always defines the attributes and that the variable
> assignment always begins from the third word."
> 
> The above is an argument for why `--` should be kept. But what if the
> 2nd argument starts with - then it is an option, otherwise it is not.

Let's cut to the chase and consider why someone might be exploiting this 
(almost 14 year old) behaviour in a script. Imagine, if you will, that someone 
wishes to iterate over the names of variables and check their attributes. Below 
is an example of how that might be accomplished.

# Print all variable names that have the both the "i" and "r" attribute set
while IFS= read -r name; do
        read -r _ attr _ < <(declare -p -- "$name")
        if [[ $attr == *i* && $attr == *r* ]]; then
                printf '%s\n' "$name"
        fi
done < <(compgen -A variable)

On my system, that prints:

EUID
PPID
UID

Nowadays, it would be preferable to use ${param@a} expansion to expand the 
attributes but that is not the point. The point is that the change that you 
propose would break code of this sort.

> This is an equally valid argument why -- is not absolutely necessary.

I do not contend that it is absolutely necessary. However, the fact that it's 
worked in the way that it currently does since at least bash-4.0 cannot be so 
readily dismissed.

> Thus, for human readability/brevity, it should not be there.

Perhaps it ought to have been so but it is by no means a forgone conclusion 
that your desire for brevity outweighs the aforementioned considerations.

-- 
Kerin Millar



reply via email to

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