2

In I have a function which should export some variables, but it doesn't.

Here an example:

function f() {

  # ...
  declare -rx TIMESTAMP_FORMAT='+%Y-%m-%d %H:%M:%S'
  # ...

}

What is the correct way of doing this from within a function?


My environment

v3.2.48(1)-release 10.8.3


2 Answers 2

2

to declare the variable as global use the option -g. Like this:

function f() {

  # ...
  declare -grx TIMESTAMP_FORMAT='+%Y-%m-%d %H:%M:%S'
  # ...

}

quote from help declare :

-d create global variables when used in a shell function; otherwise ignored


Update After reading your last comment:

Available outside the function and available in subshells

... it looks like export is the command you are looking for. Check this example:

function foo {
    export BAR="test"
}

# call function
foo

# will output 'test'
echo "$BAR"

# as the var is in environemt:
export -p | grep "BAR"

# ... it will be available from sub shells as well

Note: The export solution is missing the -r (read-only) feature from declare. If you can live with this, export should be ok.

Sign up to request clarification or add additional context in comments.

6 Comments

-bash: declare: -g: invalid option
Sorry I've not tested with bash 3.2.48. I've tested with 4.2.24 Can you upgrade?
Wich system still uses 3.2.48 ? (Will need for testing and further help). What do you mean with export ? exporting to environment?
@Robottinosino What do you mean with export? exporting to environment?
Bash 4.2 is the earliest version to have -g for declare. It's a really new feature.
|
0

Don't use declare and your variable will be available outside function as well.

function f() {
  # ...
  TIMESTAMP_FORMAT='+%Y-%m-%d %H:%M:%S'
  # ...
}

f # call your function
echo "OUTSIDE: " $TIMESTAMP_FORMAT

4 Comments

Move the declare outside the function then - if the value is intended to be used globally (I include new processes in that term), it makes sense to declare it in that scope.
What is the purpose of -x then? man says: Mark names for export to subsequent commands via the environment??
subsequent commands via the environment in the present context i.e. inside that function.
Alright.. so declare -x is absolutely identical to no use of declare -x at all, in all cases?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.