使用 bash 撰寫此腳本。出于某種原因,我的第二個 IF 條件不起作用。當條件為假時,我永遠不會收到“錯誤結果”的訊息。順便說一句,我需要再嵌套兩個 if 條件,但想讓第一個作業。有什么建議么?
if [[ condition == "true" ]] ; then
echo "TRUE result"
if [[ condition == "false" ]] ; then
echo "FALSE result"
fi
fi
uj5u.com熱心網友回復:
這里有兩個問題。第一個是condition固定字串,永遠不會等于“true”或“false”。如果它應該是一個變數,則需要使用"$condition"它來獲取它的值($獲取變數的值是必需的,有時需要雙引號以避免對 value 進行奇怪的決議)。所以像if [[ "$condition" == "true" ]] ; then.
第二個問題是,由于第二個if嵌套在第一個內部,如果第一個條件為假,它將永遠不會被測驗。也就是說,如果$condition是“假”,它會測驗它是否等于“真”,因為不是,它會跳過所有內容到最后一個fi,因此永遠不會將它與“假”進行比較。
您可能想要的是一個elif(“else if”的縮寫)子句而不是嵌套的子句if- 這樣它只會在第一個失敗時進行第二次測驗,而不是只有在它成功時。請注意,elif子句不是嵌套的,而是原始if陳述句的擴展,因此不需要額外fi的來關閉它。所以是這樣的:
if [[ "$condition" == "true" ]] ; then
echo "TRUE result"
elif [[ "$condition" == "false" ]] ; then
echo "FALSE result"
fi
如果您將某個內容與可能的字串/模式串列進行比較,最好使用以下case陳述句:
case "$condition" in
true)
echo "TRUE result" ;;
false)
echo "FALSE result" ;;
maybe)
echo "MAYBE result" ;;
*)
echo "Unrecognized result" ;;
esac
uj5u.com熱心網友回復:
@gordondavisson 嘗試了您的建議,但沒有成功。這是我的腳本,你發現有什么問題嗎?
read hostname
for x in $hostname
do
`nc -z $hostname 22`
if [[ "$hostname" == "host1" || "$hostname" == "host2" ]] ; then
message1=$(ssh -q -t adminuser@$x /usr/bin/sudo systemctl is-active sc4s.service )
echo "The SC4S service on" $hostname "is" $message1
elif [[ $message1 == "inactive" ]] ; then
echo "The SC4S service on" $hostname "is" $message1 "Please run the startsplunk script to
restart the service"
fi
done
uj5u.com熱心網友回復:
read -p "Enter hostname(s): " HOSTS
for host in $HOSTS
do
echo "Test ssh-port on $host"
nc -zv -w 2 $host 22
if [ $? -ne 0 ]; then
echo "$host is not reachable.. See message above. Check hostname/ssh-deamon/firewall"
continue
fi
if [ "$host" = "host1" -o "$host" = "host2" ] ; then
message=$(ssh -q -t adminuser@$host "/usr/bin/sudo systemctl is-active sc4s.service")
echo "The SC4S service on $host is $message"
[ "$message" = "inactive" ] && echo "Please run the startsplunk script to restart the service on $host"
fi
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/478101.html
