4

I have an environment variable for my CodeBuild environment, DiscordWebhook. This contains a URL as plaintext. I am trying to run the sed command as below. This is specified in the BuildSpec.yml file.

sed -i 's/discordWebhookAddressLocal/${DiscordWebhook}/g' scripts.js

Obviously, this just replaces all instances of discordWebhookAddressLocal with "${DiscordWebhook}". I have tried some other methods such as using an alias command, but when I try to execute the alias, CodeBuild fails saying that the command could not be found.

How can I specify an environment variable into the command?

August Williams
  • 907
  • 4
  • 20
  • 37

2 Answers2

4

This probably happens because you are using single quotes. Normally you would use double quotes to resolve the variables:

sed -i "s/discordWebhookAddressLocal/${DiscordWebhook}/g" scripts.js
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • When CodeBuild runs this command, it fails with the following error: `sed: -e expression #1, char 38: unknown option to `s'` – August Williams Oct 07 '20 at 12:13
  • @AugustWilliams From [here](https://stackoverflow.com/questions/24705650/sed-unknown-option-to-s-in-bash-script) it seems you have extra slash somewhere. Maybe in the `DiscordWebhook` variable? – Marcin Oct 07 '20 at 12:18
  • Yes, there are multiple forward slashes in the `DiscordWebhook` address, its a URL endpoint. Do I need to escape them? – August Williams Oct 07 '20 at 12:20
  • @AugustWilliams Check the link I provided. They give some ideas how to deal with it. It's difficult for me to give more details. But at least `${DiscordWebhook}` resolves now which was your original issue reported. – Marcin Oct 07 '20 at 12:22
3

It turns out that there were two separate problems in my case.

First of all, as Marcin has pointed out - double quotes should be used instead of single quotes when using variables. Secondly, the environment variable in question was a URL and had \ characters in it. This was the same character being used as a delimiter in the sed command. To remedy this, I changed the delimiter used in the sed command.

The new, complete working command looks like this:

sed -i "s|discordWebhookAddressLocal|${DiscordWebhook}|g" scripts.js

The commnad now returns no errors at all, and replaces strings inside scripts.js as expected.

August Williams
  • 907
  • 4
  • 20
  • 37