herhuf
herhuf

Reputation: 517

Use perl to replace some string in file with complicated password

I want to use perl in a bash script to replace some string in a text file with other strings that may contain various special characters (passwords). The variables containig the special characters come from the environment, so I cannot know them.

For example

# pw comes from the environment and I cannot be sure about it's content
pw='%$&/|some!\!smart%(]password' 
pw=${pw//:/\\:}
perl -p -e "s:PASSWORD:$pw:" <<< "my pw is: PASSWORD" # this would come from a text file
# yields: my pw is: %PASSWORD/|some!!smart%(]password

Here I use : as a delimiter and escape possible occurences before, which should prevent some errors. But executing this does show that this isn't even remotely working as expected, though. The bash expansion is still messing up the password.

Now my question is: How can I safely take some environment variable and place it somewhere else? What might be a better approach? I could of course replace and escape further characters in the unknown variable but how can I ever be sure if this is enough?

Upvotes: 1

Views: 123

Answers (1)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185530

Using the proper ENV special variable:

pw='%$&/|some!\!smart%(]password' 
export pw=${pw//:/\\:}
perl -pe 's:PASSWORD:$ENV{pw}:' <<< "my pw is: PASSWORD" 

Upvotes: 1

Related Questions