0

Here is an example from https://unix.stackexchange.com/a/56846/674

A different, bash-specific way of testing whether a variable of any type has been declared is to check whether it's listed in ${!PREFIX*}:

case " ${!foobar*} " in
  *" foobar "*) echo "foobar is declared";;
  *) echo "foobar is not declared";;
esac
  1. If I am correct, to make a parameter not declared, we use unset builtin. The unset case works like the quote said,

    $ unset foobar
    $ case " ${!foobar*} " in
    >   *" foobar "*) echo "foobar is declared";;
    >   *) echo "foobar is not declared";;
    > esac
    foobar is not declared
    

    but the declared case doesn't:

    $ unset foobar
    $ declare foobar
    $ case " ${!foobar*} " in
    >   *" foobar "*) echo "foobar is declared";;
    >   *) echo "foobar is not declared";;
    > esac
    foobar is not declared
    

    Is this a correct way to test if a parameter is declared?

  2. Also in " ${!foobar*} ", why are there spaces before and after the parameter expansion? Does it work when foobar is an array or dictinary and when it is a variable but not an array or dictionary?
1
1
  1. Looks like you'd have to declare the variable with a value (can be null):

    unset foobar; declare foobar=
    

    The case statement will produce "foobar is declared".

  2. you use quotes and spaces so the *" foobar "* can detect the specific variable name out of the list of varnames returned by ${!foobar*}:

    $ unset foobar; foobarbaz=1; foobarquz=2
    $ echo " ${!foobar*} "
     foobarbaz foobarquz 
    

    The case statement will produce "foobar is not declared".

2
  • Thanks. I am a little confused. What does *" foobar "* expand to? Does * match any string, so foobarbaz should be in *" foobar "*?
    – Tim
    May 2 '16 at 22:02
  • In that context, it's a pattern where * will match zero or more of any character. We are checking if the string " foobar " is contained in the string " ${!foobar*} " May 2 '16 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.