rgov
rgov

Reputation: 4329

Nullglob breaks array declaration printing

On GNU bash, version 3.2.57, I am seeing a conflict between using declare to print an array variable and the nullglob option.

These two seem to me to be very unrelated, but is this intentional when nullglob is enabled?

#!/bin/bash

test () {
  local FOO="xyz"
  local BAR=("one" "two" "three")
  declare -p FOO
  declare -a -p BAR
}

echo $(test)
shopt -s nullglob
echo $(test)
shopt -u nullglob
echo $(test)

Output:

declare -- FOO="xyz" declare -a BAR='([0]="one" [1]="two" [2]="three")'
declare -- FOO="xyz" declare -a
declare -- FOO="xyz" declare -a BAR='([0]="one" [1]="two" [2]="three")'

Note on the middle line, when nullglob is set, no declaration for BAR is emitted.

Upvotes: 1

Views: 107

Answers (2)

PhilR
PhilR

Reputation: 5592

By not quoting the echo $(test) then $(test) part is subject to pathname expansion. The result of declare -p contains [] chars which are checked against the filesystem. When nullglob is set and there are no matching files, then the word is removed.

Try setting shopt -s failglob to see what's happening in more detail; the lack of matching files will cause an error.

Upvotes: 1

anubhava
anubhava

Reputation: 785196

Problem is not nullglob but not quoting the echo command.

If you quote it then it should work fine:

shopt -s nullglob
echo "$(test)"
declare -- FOO="xyz"
declare -a BAR='([0]="one" [1]="two" [2]="three")'

Without quoting shell is attempting to expand the output of test function as there are many glob characters in the output.

When nullglob is set then expansion fails and nothing is printed for failed glob expression.

Upvotes: 2

Related Questions