-1

I have a problem that I am not able to solve, i need replace values of text variable in sh by the value of local variables. Example:

~/Documents$ VERSION=1.0.0
~/Documents$ TEST='This is a test, VERSION: $VERSION'
~/Documents$ echo $TEST
This is a test, VERSION: $VERSION

I would like to transform the TEST string so that it uses the values ​​of the local variables. I know I could change the ' ' to " " and that would work, but in my problem I get a literal string so I can't just do that.

Edit: I am trying to convert a literal string into a string with replacement of values ​​by local variables in words beginning with "$", I could do this with a simple regex but I am looking for a better way, I believe that you should achieve this using only simple SH commands.

  • There is no way to make single quotes not quote a string completely verbatim. – tripleee Mar 17 '21 at 12:34
  • 2
    Tangentially, [quote the argument to `echo`](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) unless you can be completely sure that it does not contain shell metacharacters. – tripleee Mar 17 '21 at 12:35
  • I am trying to convert a literal string into a string with replacement of values ​​by local variables in words beginning with "$", I could do this with a simple regex but I am looking for a better way. – Rafael Gruhn Mar 17 '21 at 15:03
  • I added a new duplicate which hopefully does what you want. Still not sure I understand. – tripleee Mar 17 '21 at 20:38

1 Answers1

0

If TEST must be a literal string, you can use parameter substitution. These are bash docs, but it also works in sh:

${var/Pattern/Replacement}: First match of Pattern, within var replaced with Replacement. If Replacement is omitted, then the first match of Pattern is replaced by nothing, that is, deleted.

${var//Pattern/Replacement}: Global replacement. All matches of Pattern, within var replaced with Replacement.

For your given example, it would be ${TEST/\$VERSION/$VERSION}:

$ VERSION=1.0.0
$ TEST='This is a test, VERSION: $VERSION'
$ echo "${TEST/\$VERSION/$VERSION}"
This is a test, VERSION: 1.0.0

The first dollar sign is escaped so the Pattern is \$VERSION which becomes the literal string "$VERSION". Then its Replacement is $VERSION which gets interpolated as "1.0.0".

tdy
  • 36,675
  • 19
  • 86
  • 83
  • 1
    "I know I could change the '' to "" and that would work, but in my problem I get a literal string so I can't just do that." I appreciate the help but I get the value as a text, I can't do that – Rafael Gruhn Mar 17 '21 at 14:28
  • Sorry you're right, I skimmed too quickly and I guess the mods did too when they closed it. – tdy Mar 17 '21 at 17:42
  • You can do this in pure `sh` with parameter substitution. I edited my answer. – tdy Mar 17 '21 at 17:42