bashshellvariables

Assigning existing variable value to a new variable


I want to assign a value of an existing variable to a new variable. The issues is that once the new variable gets assigned to a value of the existing variable it returns none instead of returning the existing variable value.

VAR1="Hello World"
VAR2="Let's concatenate"

VAR1+="$MyVar" # assigning to a new variable
echo "$VAR1"
echo "$MyVar" # This is the issue --> no value returned (intention is to return "Hello World")

The output is for this command (echo "$MyVar") is:

+ VAR1=
+ echo ''

Solution

  • You aren't defining a new variable named MyVar. You are appending the empty string resulting from the expansion of the non-existent variable to the value of VAR1.

    You want

    MyVar=$VAR1
    

    to get the desired result.


    An example of what += does do:

    $ x=foo
    $ echo "$x"
    foo
    $ x+=bar
    $ echo "$x"
    foobar