开发者

How to use declare -x in bash

Can some one give an example where declare -x would be开发者_C百科 useful ?


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.


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


Use declare -x when you want to pass a variable to a different program, but don't want the variable to be used in global scope of the parent shell (i.e. when declaring inside a function).

From the bash help:

When used in a function, declare makes NAMEs local, as with the local command. The -g option suppresses this behavior.

-x to make NAMEs export

Using + instead of - turns off the given attribute.

So declare -gx NAME=X will effectively behave the same as export NAME=X, but declare -x does not when the declare statements are inside functions.


The accepted solution is not accurate, as commented by @sampablokuper. However both export variable a to subshells (below within ()).
test.sh:

#/bin/bash
foo() {
    declare -x a="OK"
    ([ "$a" = "OK" ]) &&  echo "foo exported a locally"

}

bar() {
    export a="OK"
    ([ "$a" = "OK" ]) && echo "bar exported a locally"
}

foo
echo "Global value of a by foo: ${a}"  
([ "$a" = "OK" ]) &&  echo "foo exported a globally" \
                  || echo 'foo did not export a globally'
bar
echo "Global value of a by bar: ${a}"  
([ "$a" = "OK" ]) && echo "bar exported a globally" \
                  || echo 'bar did not export a globally'

Runs as follows:

$ ./test.sh
foo exported a locally
Global value of a by foo: 
foo did not export a globally
bar exported a locally
Global value of a by bar: OK
bar exported a globally
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜