我有一個功能,我想用來獲取/檢查網站證書。我使用ZSH,但也想在BASH中測試它,以驗證它在shell中的工作情況。Bash沒有從函數中打印換行符?
該函數似乎將內容打印爲一行,並且沒有注意到或保留openssl命令的換行符。 ZSH處理它就好,按預期工作。
如何在openssl命令返回時讓bash注意到新行?
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
}
你可能想看看這篇文章:爲什麼?是的printf比回聲更好(http://unix.stackexchange.com/questions/65803/why-is-printf-better-than -echo) – codeforester
如果你遵循最佳實踐,問題就會消失。絕對不需要捕獲openssl的輸出,然後回顯它。如果不是'content = $(openssl ...);如果......''你剛剛做了'openssl ...',輸出將轉到標準輸出並且該函數將返回非零而不是零。只需將函數的最後一行調用openssl即可。 –
@WilliamPursell我封裝它的原因是因爲OpenSSL嘗試連接,如果你輸入一個錯誤的域,並且它沒有一個證書,或者特別是沒有監聽443它掛起,因爲它默認爲端口443,如果你鍵入'get -cert purple.com'而不是'get-cert purple.com 80' – LF4