schone
schone

Reputation: 572

bash variable reevaluation

This is a total newbie question but i'm struggling so I apologize.

I'm using bourne shell for an init script.

I have a variable A=1 B="Welcome to world #$A"

Somewhere down the script i have a loop that updates A to 2,3,4 etc... How do I get B to get re-evaluated? At present, B stays "Welcome to world #1" the whole time.

Thanks!

UPDATE #1 - some code:

#!/bin/sh

A=1
B="Welcome to #$A"

repeatloop() {
  for i in {1..5}
  do
    A=$i
    echo $B
  done
}

repeatloop

Output:

Welcome to #1
Welcome to #1
Welcome to #1
Welcome to #1
Welcome to #1

I'm trying to get #2,#3,#4....

Upvotes: 4

Views: 2338

Answers (4)

Noam Manos
Noam Manos

Reputation: 17040

You can set your B argument as an eval statement. Then just call it inside the loop:

#!/bin/sh

A=1
B='eval echo "Welcome to #$A"'

repeatloop() {
  for i in {1..5}
  do
    A=$i
    $B
  done
}

repeatloop

Output:

Welcome to #1
Welcome to #2
Welcome to #3
Welcome to #4
Welcome to #5

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360683

You will need to do the assignment to B each time you do the assignment to A:

#!/bin/sh

A=1
B="Welcome to #$A"

repeatloop() {
  for i in {1..5}
  do
    A=$i
    B="Welcome to #$A"
    echo $B
  done
}

repeatloop 

By the way #!/bin/sh is not Bash (even if it's a symlink to it).

Upvotes: 2

f0ster
f0ster

Reputation: 558

The problem is, B is set with the value of what A currently is. If you want it to update, you'll have get it from a function that recreates the value of B with the new value of A.

Think about it in another language like c/java.

int a = 0;
string b = "blah blah blah" + a; // b= "blah blah blah0"
a = 4;
//b still equals "blah blah blah0"

Upvotes: 0

Amber
Amber

Reputation: 527438

When you type...

B="Welcome to the world #$A"

the value of $A is expanded before assigning a value to B. Which means that what you've typed there is equivalent to...

B="Welcome to the world #1"

So "re-evaluating" makes no sense, because B doesn't actually have a variable in it.

If you want variables to not be expanded until something is actually referenced, use a function instead:

function B() {
    echo "Welcome to the world $1"
}

A=1
welcomeone=$(B $A)

A=2
welcometwo=$(B $A)

Upvotes: 1

Related Questions