1

I have a bash script that reads a file that contains strings and I want to do some variable substitution before executing the commands. It's pretty much what bash does itself. The user will provide an array of substitution arguments to the script. This seems pretty simple but I can't get the $ to be substituted in the string read from the file. Assume the STR is being read from a file and the ARGS are input to the script:

#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   #STR=`echo $STR | sed "s/'$'{$v}/$s/g"` #using this replaces nothing in STR
   STR=`echo $STR | sed "s/{$v}/$s/g"   #using this replaces the {number} correctly but leaves the $
   v=$((v+1))
done
echo $STR
# eval $STR

Running the above, gives: This is $what my input $string string looks like. $what? but I want the $ to not be there in the final STR.

2
  • is string in bash script or how to in a bash script replace a $ in a string with a variable ? Commented Jun 22, 2020 at 20:49
  • not understanding completely; might be helpful to see some input from a file or whatever you expect from cli. Commented Jun 22, 2020 at 20:52

1 Answer 1

1
#!/bin/bash
ARGS=(what string)
STR='This is ${1} my input ${2} string looks like. ${1}?'

v=1
for s in "${ARGS[@]}"
do
   STR=`echo $STR | sed "s/\\${$v}/$s/g"`
   v=$((v+1))
done
echo $STR

This gets me this output, if I understood you correctly it is what you wanted.

This is what my input string string looks like. what?
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I needed. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.