有沒有辦法編寫一個更優雅的代碼,它考慮多種可能的組合而不是編寫冗長的if-else語句?在bash中改進long if-else語句
我有隨機生成的數據集像下面的那些,但有些行有時可能爲空。
{
semester1 grade1 final_grade1
semester1a grade1a final_grade1a
}{
semester2 grade2 final_grade2
semester2a grade2a final_grade2a
}
我已經WR我的數據的所有可能的邏輯組合伊頓代碼:
if [[ -n $semester1 && -z $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."
elif [[ -n $semester1 && -n $semester1a && -z $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."
elif [[ -n $semester1 && -n $semester1a && -n $semester2 && -z $semester2a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a."
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."
elif [[ -n $semester2 && -z $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, final grade for $semester2=$final_grade2 ."
elif [[ -n $semester2 && -n $semester2a && -z $semester1 && -z $semester1a ]]; then
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."
elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -z $semester1a ]]; then
echo "Section 1:$semester1=$grade1, final grade for $semester1=$final_grade1 ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."
elif [[ -n $semester2 && -n $semester2a && -n $semester1 && -n $semester1a ]]; then
echo "Section 1:$semester1=$grade1, $semester1a=$grade1a, final grade for $semester1=$final_grade1, final grade for $semester1a=$final_grade1a, ."
echo "Section 2:$semester2=$grade2, $semester2a=$grade2a, final grade for $semester2=$final_grade2, final grade for $semester2a=$final_grade2a, ."
fi
有沒有檢查這更好的辦法?
什麼定義更好?任何代碼行數較少的代碼可能更難以讓另一個人維護。至少在這裏,意圖是什麼是無法理解的。 (將被bash精英的成員證明是錯誤的;-)。祝你好運。 – shellter
[codereview.se]通常更歡迎在沒有提出特定技術問題的情況下改進工作代碼的問題。 –
我喜歡這個問題。真值表(這本質上是這樣)是可愛的,但很少有腳本語言似乎支持它們作爲數據結構。對我來說,這感覺就像是在計算機科學中錯過了一次機會。 – sampablokuper