3

I am want to change a global variable (or at least append to it) using a function.

input="Hello"
example=input    

func() {
    declare -x $example="${input} World"
}

func
echo $input

The output of this would be "Hello" The original value. I would like it if the function were to able to change the original value. Is there alternative to accomplishing this. Please note I need to set example=input and then perform on the operation on example (the variable).

BTW, if I used eval instead the function will complain about World being a function or something.

3 Answers 3

6

Did you try using export?

export $example="${input} World"
Sign up to request clarification or add additional context in comments.

Comments

3

you should use

declare -x -g $example="${input} World"

in your func

The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases.

see

http://www.gnu.org/software/bash/manual/bashref.html

Also note in MinGW, it seems that declare does not support the -g option.

1 Comment

you can combine those declare -gx Also declare -x will export but only within the scope of the function. See related question stackoverflow.com/a/5785683/4695378
0

You could use eval by redefining func() as the following:

func() {
    eval $example=\"${input} World\"
}

This allows the double-quotes to "survive" the first parsing (which expands the variables into their values, as needs to be done) so that eval starts parsing again with the string 'input="Hello World".

As for the use of export to do the job, if the variable input does not actually need to be exported, include its '-n' option:

export -n $example=...

, and the variable remains a shell variable and does not get exported as an environment variable.

2 Comments

Using eval is generally frowned upon, because it opens you to command injection attacks if you have any untrusted user input.
... if there is a better way. Bash <v4.3 does not support declare -g and if export would not work for specific case, eval would be the only option here. In this answer, script could be hacked by input='ha"; date; "' but easy fix is to add single quotes: eval '$example=\"${input} World\"' and this eval will be safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.