1

I want to know how to get a string variable containing a variable in the string to interpolate the contained variable dynamically --each time it is referenced.

This is best explained with example code.

#!/bin/bash
VAR1="string of var1 $VAR2"

function function1()
{
  echo "$1 $VAR1"
}

function function2()
{
  VAR2="$1"
}

function2 1000

function1 "example 1:"

function2 2000

function1 "example 2:"

The output is:

example 1: string of var1
example 2: string of var1

But the desired output is:

example 1: string of var1 1000
example 2: string of var1 2000

The problem with this is that VAR1 is evaluated only once at run-time, when the desired effect would be for it to be evaluated every time it is referenced. When the string of VAR1 is interpolated within function1, VAR2 will already have been interpolated at the variable declaration, and be empty.

Obviously this is a contrived example, but it's not too hard to imagine having a variable that changes often as part of a string literal.

I have tried escaping VAR2 as \$VAR2 and using hard quotes on the string literal of VAR1. Both result in the literal string "string of var1 $VAR2"

I have also tried using eval like eval "echo "$1 $VAR1"" but that fails to work and starts getting tricky escaping the quotes.

Yes, I know that you can refactor the whole thing to get it to work. That is not a suitable answer to the problem.

  • Since you've eliminated all the suitable answers from contention... – Michael Homer Aug 7 '17 at 19:41
  • 2
    Variables are not dynamic; their value is changes only on assignation of a new value. If you want something dynamic, you will need a function (or alais). – DopeGhoti Aug 7 '17 at 19:59
3

As @DopeGhoti said in a comment, variables are not dynamic; they store static data, not instructions for generating data. If you want something that'll produce different data each time it's run, use a function, and then reference it with $():

dynamic_thing()
{
    echo "string of dynamic_thing $VAR2"
}

function function1()
{
  echo "$1 $(dynamic_thing)"
}

function function2()
{
  VAR2="$1"
}

function2 1000

function1 "example 1:"

function2 2000

function1 "example 2:"

The output is:

example 1: string of dynamic_thing 1000
example 2: string of dynamic_thing 2000
0
VAR1='string of var1 $VAR2'
function function1()
{
  eval echo \"'$1 $VAR1'\"
}
  • This did not work for me using Bash 4.1.2(1)-release. – typedeaf Aug 8 '17 at 19:24
  • @typedeaf Sorry, wrong quoting – Hauke Laging Aug 8 '17 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.