我有点困惑,输出与参数printf
中指定的不同FORMAT
:
$ 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
怎么/为什么?如何获得想要的输出?
如果我直接传递字符串(而不是从变量),那么我会得到预期的输出:
$ 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"}
只是为了补充已接受的答案,在我的PWD_HASH
I 中,有来自docker exec -t
.显然,行尾使用的TTY
是CRLF
( \r\n
),因此出现了意想不到的\r
...
答案1
您的变量在字符串末尾PWD_HASH
包含一个回车符,它将最后两个字符移动到输出的开头。\r
"}
例子:
$ 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