I'm trying encrypt a password and replace the word "notset" with this new encrypted password. The problem is that openssl sometimes creates a string with more than one line, like:

Salted__▒ہ▒ >▒▒1▒▒▒E

So, when I run sed, it fails.

Here is the command I'm using:

sed -i 's/PASSWORD=.*/PASSWORD='${P}'/' ${PFILE}

And the error I'm receiving is:

sed: -e expression #1, char 49: unterminated `s' command

Anyone knows how can I replace the whole string, when it has this line brake? I tried using this before:

P=`echo ${P} | tr '\n' "\\n"`

but it didn't help.

  • Possible duplicate of Variable in sed
    – muru
    Jun 24 '19 at 16:04
  • By keeping ${P} outside quotes, it undergoes word-splitting, that's why the newline is a problem. Keep it within quotes.
    – muru
    Jun 24 '19 at 16:04
  • @muru That's one issue. The other being the actual newline in the password.
    – Kusalananda
    Jun 24 '19 at 16:23
  • 4
    @AlexanderRumanovsk You would have less trouble with special characters if you would use base64 encoding using the -base64 option.
    – Freddy
    Jun 24 '19 at 17:00
  • 1
    The output of openssl enc may contain nul bytes, so you simply cannot store the binary garbage in a variable. Most shell do not support nul bytes in variables, and even with those that do, they cannot be passed as arguments to other commands. Yours is an XY-problem.
    – mosvy
    Jun 25 '19 at 8:43

A variable can not contain arbitrary binary values (in most shells).

By creating the value of P like this:

P=$( echo 'mysuperpassword3' | 
          openssl enc -aes-256-cbc -pbkdf2 -pass pass:'secret')

you are exposed to NUL bytes, newlines, $var expansions and many other problems. One possible solution is to store the value in a base64 encoded form:

P=$( echo 'mysuperpassword3' | 
          openssl enc -aes-256-cbc -pbkdf2 -base64 -pass pass:'secret')

That would avoid many issues but still: variable expansions should be quoted:

sed -i 's/PASSWORD=.*/PASSWORD='"${P}"'/' "${PFILE}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.