2

I have a function I wanted to use for getting/checking website certs. I use ZSH but wanted to test it in BASH as well to verify that it works as well in that shell.

The function seems to print out the content as a single line and isn't noticing or keeping the newlines from the openssl command. ZSH handles it just fine and works as expected.

What can I do to get bash to notice the new lines when the openssl command returns?

function get-cert() {
if (( $# == 2 )); then
    site_url=${1}
    site_port=${2}
elif (( $# == 1 )); then
    site_url=${1}
    site_port=443
else
    echo -n "Enter site domain to get and view the cert: "
    read site_url
    echo -n "Enter the port [443]: "
    read site_port
    site_port=${site_port:-443}
fi

echo " === Getting cert for site ${site_url}:${site_port}"
content="$(openssl s_client -showcerts -servername ${site_url} -connect ${site_url}:${site_port} </dev/null)"
if [[ $? == "0" ]]; then
    echo ${content}
else
    echo "Failed to get cert for ${site_url}"
fi
}
krizzo
  • 1,823
  • 5
  • 30
  • 52
  • You may want to take a look at this post: [Why is printf better than echo?](http://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) – codeforester Feb 13 '17 at 22:43
  • The problem would simply go away if you followed best practice. There is absolutely no need to capture the output of openssl and then echo it. If instead of `content=$(openssl...); if ...` you just did `openssl...`, the output would go to stdout and the function would return non-zero instead of zero. Just make the last line of the function a call to openssl. – William Pursell Feb 14 '17 at 00:44
  • @WilliamPursell The reason I wrapped it was due to OpenSSL's attempt to connect if you type a wrong domain and it doesn't have a cert or specifically isn't listening on 443 it hang because it defaults to port 443 if you type `get-cert purple.com` instead of `get-cert purple.com 80` – krizzo Feb 15 '17 at 21:17
  • If openssl hangs, it will still hang. If it fails, it will print an error message. If openssl is producing verbose output to stdout when it fails, then wrapping it this way can be useful but otherwise it's just causing unnecessary problems. – William Pursell Feb 15 '17 at 22:51

1 Answers1

4
echo ${content}

This line breaks content into words and passes each word as an argument to echo, which separates them with spaces. Wrap it in quotes.

echo "${content}"
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • Agh, I quoted the "$()" but not the content thanks for pointing that out. That fixed it. Thanks. – krizzo Feb 13 '17 at 22:25
  • 6
    Ironically, you didn't need to quote the `$()`, because an expansion on the right-hand side of an assignment is not subject to word-splitting or pathname expansion. – chepner Feb 13 '17 at 22:31