Home > Software engineering >  Bash - Assigning existing Variable values to a New Variable. New Variable values does not return the
Bash - Assigning existing Variable values to a New Variable. New Variable values does not return the

Time:10-30

I want to assign a value of the existing Variable to a new Variable in my Bash script. 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. (see code below):

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 ''

enter image description here

CodePudding user response:

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
  • Related