Home > Software engineering >  bash script, to use a variable in a variable
bash script, to use a variable in a variable

Time:09-17

In order to obtain the results of consecutive numbers, a bash script was created as follows. However, the results did not come out as intended.

#!/bin/bash

test="i am $i"

for i in {1..10}
do
        echo "$test"
done

result

sh test.sh

i am 
i am 
i am 
i am 
i am 
i am 
i am 
i am 
i am 
i am 

But the result I want is... As shown below, how do we deal with the variables to get the results?

i am 1
i am 2
i am 3 
i am 4
i am 5
i am 6
i am 7
i am 8
i am 9
i am 10

CodePudding user response:

Use $i outside of the variable

#!/bin/bash

test="i am "

for i in {1..10}
do
  echo $test $i
done

Also you can use ${i} inside of the variable

#!/bin/bash

for i in {1..10}
do
  test="i am ${i}"
  echo $test
done

The result is:

i am  1
i am  2
i am  3
i am  4
i am  5
i am  6
i am  7
i am  8
i am  9
i am  10

Or you can replace substr with anything you want inside.

For example

#!/bin/bash
test="I am SUBSTR"

for i in {1..10}
do
  echo ${test/SUBSTR/$i}
done

When you have multiple variables, I know this solution:

#!/bin/bash
test="I am SUBSTR and STR2"

for i in {1..10}
do
  o=${test/SUBSTR/$i}
  echo ${o/STR2/$i*$i}
done

Using sed also can help

#!/bin/bash
test="I am SUBSTR and STR2"

for i in {1..10}
do
  echo $test | sed  -e 's/SUBSTR/'$i'/;s/STR2/'$i  '/'
done

CodePudding user response:

You need to write a function in order to delay the evaluation.

#!/bin/bash

message () { echo "i am $1"; }

for i in {1..10}
do
  message $i
done

Or the following, if you just want to craft the message.

#!/bin/bash

message () { echo "i am $1"; }

for i in {1..10}
do
  test="$(message $i)"
  echo "$test"
done

CodePudding user response:

#!/bin/bash

test='i am $i'

for i in {1..10}
do
  eval echo "$test"
done

or

#!/bin/bash

test='echo "i am $i"'

for i in {1..10}
do
  eval "$test"
done

Example:

yanyong@master:~$ test='echo "i am $i"'; for i in {1..10}; do eval "$test"; done
i am 1
i am 2
i am 3
i am 4
i am 5
i am 6
i am 7
i am 8
i am 9
i am 10

References:

https://man7.org/linux/man-pages/man1/eval.1p.html

  • Related