0

I'm a little confused, the output from the printf is different than specified in the FORMAT argument:

$ echo "$PWD_HASH"
{SHA512-CRYPT}$6$ZLgRL2DZSKYUCzht$PaTcpkoOi6P6p9ItIjRTL00MCB/8IU.fJbGk9EO/LxUAgZwGASO6qXNSNSzxQRBGjNiPpiArgwOacZSG5A6FL1
$ PWD_JSON=$(printf '{"password": "%s"}' "$PWD_HASH")
$ echo "$PWD_JSON" 
"}password": "{SHA512-CRYPT}$6$ZLgRL2DZSKYUCzht$PaTcpkoOi6P6p9ItIjRTL00MCB/8IU.fJbGk9EO/LxUAgZwGASO6qXNSNSzxQRBGjNiPpiArgwOacZSG5A6FL1

How / why? How to get the desired output?

If I pass the string directly (not from the variable), then I get the expected output:

$ PWD_JSON=$(printf '{"password": "%s"}' '{SHA512-CRYPT}$6$ZLgRL2DZSKYUCzht$PaTcpkoOi6P6p9ItIjRTL00MCB/8IU.fJbGk9EO/LxUAgZwGASO6qXNSNSzxQRBGjNiPpiArgwOacZSG5A6FL1')
$ echo "$PWD_JSON"
{"password": "{SHA512-CRYPT}$6$ZLgRL2DZSKYUCzht$PaTcpkoOi6P6p9ItIjRTL00MCB/8IU.fJbGk9EO/LxUAgZwGASO6qXNSNSzxQRBGjNiPpiArgwOacZSG5A6FL1"}

Just to complement the accepted answer, here in my PWD_HASH I have output from the docker exec -t. Apparently line-endings used by TTY are CRLF (\r\n), hence the unexpected \r...

4
  • Downvoters please leave a comment. – NarūnasK Apr 5 '20 at 11:38
  • How is it different? I tried to reproduce and got {"password": "{SHA512-CRYPT}$6$ZLgRL2DZSKYUCzht$PaTcpkoOi6P6p9ItIjRTL00MCB/8IU.fJbGk9EO/LxUAgZwGASO6qXNSNSzxQRBGjNiPpiArgwOacZSG5A6FL1"}, is this what you expect? – Arkadiusz Drabczyk Apr 5 '20 at 11:52
  • @ArkadiuszDrabczyk Yes, this is what I expect, see the edit. – NarūnasK Apr 5 '20 at 11:56
  • Side note: shell variable names should be lower-case. (there is a standard somewhere, it stops you colliding with environment variables). – ctrl-alt-delor Apr 5 '20 at 12:33
7

Your variable PWD_HASH contains a carriage return \r at the end of the string which moves the last two characters "} to the beginning of the output.

Example:

$ PWD_HASH='{SHA512-CRYPT}abcde'$'\r'
$ PWD_JSON=$(printf '{"password": "%s"}' "$PWD_HASH")
$ echo "$PWD_HASH"
{SHA512-CRYPT}abcde
$ echo "$PWD_JSON"
"}password": "{SHA512-CRYPT}abcde
$ echo "$PWD_JSON" | od -c
0000000   {   "   p   a   s   s   w   o   r   d   "   :       "   {   S
0000020   H   A   5   1   2   -   C   R   Y   P   T   }   a   b   c   d
0000040   e  \r   "   }  \n
0000045
1
  • Also, printf -v PWD_JSON 'format string' values (as a convenience in place of an awkward command substitution). – Kusalananda Apr 12 '20 at 11:08

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.