Given:
~$ cat .test-profile
export [email protected]
export MONGODB_URI='mongodb+srv://administrator:[email protected]/test?retryWrites=true&w=majority'
I wrote the following shell script to replace the variable values:
BASH_PROFILE="$HOME/.test-profile"
MONGODB_URI="mongodb+srv://administrator:[email protected]/mysite_development?retryWrites=true&w=majority"
INSERT_ENV_VAR () {
if [[ -z "$2" ]]
then
echo "Failed to retrieve $1"
else
if grep -q "$1" "$BASH_PROFILE"; then
# Cannot use / delimiter, for value can contain /
sed -in -E "s|(export $1=)[a-zA-Z0-9@.:\/=&\-\?\+]+|\1$2|g" "$BASH_PROFILE"
else
echo "export $1=$2" >> "$BASH_PROFILE"
fi
fi
}
INSERT_ENV_VAR 'ADMIN_EMAIL' '[email protected]'
INSERT_ENV_VAR 'MONGODB_URI' $MONGODB_URI
While the ADMIN_EMAIL variable is replaced fine, the MONGODB_URI variable is not being replaced. And I believe it has to do something with the character class [] inside of the regex. But I am not sure what. I tried it in a programming language like ruby and it found the match. But with sed it isn't finding the match. Why?
This is what I expect .test-profile to look like afterwards:
export [email protected]
export MONGODB_URI='mongodb+srv://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'
Notice 'mysite_development' replaces 'test'.
'character. Try your sed with(export MONGODB_URI=)[a-zA-Z0-9@.:\/=&\-\?\+']+(adds a'to the list of valid characters).&in the replacement string."s|(export $1=).*|\1$2|"? And why useg? But you still have to escape&in$2.