arraysbashglobshopt

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.


Solution

  • 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.