How to use declare -x in bash

2019-04-06 00:06发布

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

标签: bash shell
2条回答
在下西门庆
2楼-- · 2019-04-06 00:40

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
查看更多
女痞
3楼-- · 2019-04-06 00:49

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.

查看更多
登录 后发表回答