How to use declare -x in bash

2019-04-06 00:14发布

问题:

Can some one give an example where declare -x would be useful ?

回答1:

declare -x FOO is the same as export FOO. It "exports" the FOO variable as an environment variable, so that programs you run from that shell session would see it.



回答2:

Declare -x can be used instead of eval to allow variables to be set as arguments to the shell. For example, you can replace the extremely insecure:

# THIS IS NOT SAFE
while test $# -gt 0; do
  eval export $1
  shift
done

with the safer:

while test $# -gt 0; do
  declare -x $1
  shift
done

As an aside, this construct allows the user to invoke the script as:

$ ./test-script foo=bar

rather than the more idiomatic (but confusing to some):

$ foo=bar ./test-script


标签: bash shell