Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash – echoing captured variable removes newline

I have a private key I want to both print to stdout and transform to a public key which should also be printed.

Based on this answer: Piping echo output to another echo

echo "pkcs12 here" |\ 
  openssl rsa |\
  { var=$(cat); echo "$var\n$(echo $var | openssl rsa -pubout)"; }

This works fine in ZSH, but I’ve found out that in Bash the innermost echo $var removes newline characters, which causes the openssl command to fail

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now that we know what I want to do, let’s simplify the problem a bit:

$ echo "a\nb\nc"
a
b
c
echo "a\nb\nc" | { var=$(cat); echo "$(echo $var)"; }
a b c

How do I preserve new lines in the simplified example?

>Solution :

Like this:

echo "a\nb\nc" | { var=$(cat); echo "$(echo -e "$var")"; }
a
b  
c

Learn how to quote properly in shell, it’s very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
https://web.archive.org/web/20230224010517/https://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading