简体   繁体   中英

reload a variable string inside another string

I have to declare a string composed of different variables at the starting of a loop in order to print it later just with eval $command >> file.txt avoiding retype every time the string $command itself. But my $command string is composed of other variables and I need to be able to update them before printing. Here a brief example:

a=0
command="echo \"$a\""
for i in {1..2}; do
    ### change variable $a
    a="$i"
    ### print command with the new $a
    eval "$command"
done

### (it fails) result:
0
0

I need $a to be reloaded everytime in order to be substituted inside the $command string, thus the loop above will return

### wanted result
1
2

I know there are other strategies to achieve this, but I wonder if there is a specific way to reload a variable inside a string

Thank you very much in advance for any help!

You can use a function instead of a variable assignment

#!/usr/bin/env bash

a=0 
command(){ echo "$1" ; }

for i in {1..2}; do
  a="$i" 
  command "$a"
done

Edit: as per @glenn jackman one can use a global variable

command(){ echo "$a"; }

And just call the function without the argument $a

command

When you put a variable inside " its expanded. Use a single quote for command variable assignment.

$a=0
$command="echo \"$a\""
$echo $command 
echo "0"
$command='echo \"$a\"'
$echo $command 
echo \"$a\"
$

Try

a=0
command='echo $a'
for i in {1..2}; do
    ### change variable $a
    a="$i"
    ### print command with the new $a
    eval "$command"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM