Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash variable reevaluation

Tags:

sh

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

like image 741
schone Avatar asked Oct 18 '25 15:10

schone


1 Answers

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).

like image 124
Dennis Williamson Avatar answered Oct 21 '25 02:10

Dennis Williamson