Niyaz Murshed Niyaz Murshed - 4 months ago 12
Bash Question

Base64 encoding new line

I am trying to encode some hex values to base64 in shell script.

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 ?

Online i found, use "-n" to ignore new lines...Can anyone suggest something ?

Answer

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.

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.


Assuming you have the GNU version of base64, add -w 0 to disable line wrapping in its output. Thus:

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