bash Base64 编码新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38578528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encoding new line
提问by Niyaz Murshed
I am trying to encode some hex values to base64 in shell script.
我正在尝试在 shell 脚本中将一些十六进制值编码为 base64。
nmurshed@ugster05:~$ echo -n "1906 1d8b fb01 3e78 5c21 85db 58a7 0bf9 a6bf 1e42 cb59 95cd 99be 66f7 8758 cf46 315f 1607 66f7 6793 e5b3 61f9 fa03 952d 9101 b129 7180 6f1d ca93 3494 55e0 0e2e" | xxd -r -p | base64
GQYdi/sBPnhcIYXbWKcL+aa/HkLLWZXNmb5m94dYz0YxXxYHZvdnk+WzYfn6A5UtkQGxKXGAbx3K
kzSUVeAOLg==
I get a automatic new line after 76 charecters, Is there a way to avoid that ?
我在 76 个字符后自动换行,有没有办法避免这种情况?
Online i found, use "-n" to ignore new lines...Can anyone suggest something ?
我在网上发现,使用“-n”忽略新行......有人可以提出建议吗?
回答by Charles Duffy
echo -n
doesn't actually matter here: It controls whether there's a newline on the output from echo
, but whether echo
emits a newline has no bearing on whether xxd
or base64
emit newlines.
echo -n
实际上并不无论这里:它控制是否有来自输出一个换行符echo
,但能否echo
换行发出对是否没有关系xxd
或base64
EMIT换行符。
Because xxd
ignores any trailing newline in the input, echo
or echo -n
will behave precisely the same here; whether there's a newline by echo
makes no difference, because that newline (if it exists) will be consumed by xxd
when reading its input. Rather, what you ultimately care about is the output of base64
, which is what is generating your final result.
因为xxd
忽略输入中的任何尾随换行符,echo
或者echo -n
在这里的行为完全相同;是否有换行符echo
没有区别,因为xxd
在读取其输入时将使用该换行符(如果存在)。相反,您最终关心的是 的输出base64
,这就是生成最终结果的原因。
Assuming you have the GNU version of base64, add -w 0
to disable line wrapping in its output. Thus:
假设您拥有 GNU 版本的 base64,添加-w 0
以禁用其输出中的换行。因此:
printf '%s' "1906 1d8b fb01 3e78 5c21 85db 58a7 0bf9 a6bf 1e42 cb59 95cd 99be 66f7 8758 cf46 315f 1607 66f7 6793 e5b3 61f9 fa03 952d 9101 b129 7180 6f1d ca93 3494 55e0 0e2e" \
| xxd -r -p \
| base64 -w 0
回答by A-AKN
I had a similar problem where
var1=$(echo -n "$USER:$PASSWORD" | base64)
was resulting in an erroneous base64 encoded value which was unusable in my next step of the script, used printf & it worked fine. Here is my code:
我有一个类似的问题,
var1=$(echo -n "$USER:$PASSWORD" | base64)
导致错误的 base64 编码值在脚本的下一步中无法使用,使用 printf 并且它工作正常。这是我的代码:
var1=$(printf "%s" "${USER}:${PASSWORD}" | base64)