Search code examples
stringbasheval

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!


Solution

  • 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