Home > Software engineering >  In which order are these instructions executed?
In which order are these instructions executed?

Time:09-17

I am using a shell script named script.sh that looks like that :

#!/bin/bash
STRING=$(cat my_string.txt)
${1}

In my_string.txt, there is only :

this_is_my_string

When I execute the commands :

$ STRING="not_my_string"
$ ./script.sh "echo $STRING"

The shell prints not_my_string instead of this_is_my_string and I don’t understand why. Could you explain me ? And is there any way to force to print the value of the STRING variable which is defined inside the script ?

CodePudding user response:

The variable $STRING is being expanded before the script is called, which is why not_my_string is being assigned.

To delay expansion until after the script is called you should replace "echo $STRING" with 'echo $STRING'. The single quotes cause the expansion to be delayed.

There is some discussion of delayed expansion here:

How to delay expansion of variable in bash if command should be executed on an other machine?

You will also need to replace ${1} in your script with eval ${1}, which will force the string to be executed and expanded.

CodePudding user response:

$ STRING="not_my_string"
$ ./script.sh "echo $STRING"

During command execution bash will expand all variables to the values and actually the following command will be executed: ./script.sh "echo not_my_string"

You can use the following: ./script.sh 'echo $STRING' to send string as is and eval "${1} inside the script to execute argument

  • Related