Case ステートメントが期待どおりに機能しない (fuzzytime() 関数)

Case ステートメントが期待どおりに機能しない (fuzzytime() 関数)
FuzzyTime()
{
local tmp=$( date +%H )

case $((10#$tmp)) in
    [00-05] )
        wtstr="why don't you go to bed"
        ;;
    [06-09] )
        wtstr="I see your very eager to start the day"
        ;;
    [10-12] )
        wtstr="and a very good day too you"
        ;;
    [13-18] )
        wtstr="Good Afternoon"
        ;;
    [19-21] )
        wtstr="Good Evening"
        ;;
    [22-23] )
        wtstr="it is getting late, it's time to party or go to bed"
        ;;
    *)
        wtstr="guess the planet your on has more than a 24 hour rotation"
        echo 'case value is:' $tmp
        ;;
esac
}

ケース変数は24時間で時間を表しますが、数字08と17は問題を引き起こしているようです。 08を使って問題を解決しましたが、$((10#$tmp))今17が問題になりますか?これは私の最初のbashスクリプトです。愚かな質問なら事前に申し訳ありません。

ベストアンサー1

[]文字範囲を表します。 [10-12] 数字 1 2 と数字 0-1 の範囲を示します。これは範囲内の単一の数字と一致します0-2

単純比較の使用if-elif-else-fi:

if [ "$tmp" -ge 0 ] && [ "$tmp" -le 5 ]; then
  echo "<0,5>"
elif [ "$tmp" -ge 6 ] && [ "$tmp" -le 9 ]; then
  echo "<6,9>"
  #...
else
  #...
fi

(または各間隔が必要な場合は一連の範囲制限を繰り返すことができますが、この場合は必要に応じてハードコードすることもできます。)

編集:要求されたアレイのバージョン:

FuzzyTime(){
  local needle=$1 #needle is $1
  : ${needle:=$( date +%H )} #if no needle is empty, set it to "$(date +%H)
  local times=( 0 6 10 13 19 22 24 0 ) 
  local strings=( 
          "why don't you go to bed"
          "I see your very eager to start the day"
          "and a very good day too you"
          "Good Afternoon"
          "Good Evening"
          "it is getting late, it's time to party or go to bed"
          "guess the planet your on has more than a 24 hour rotation"
          )
    local b=0
    # length(times) - 2 ==  index of the penultimate element 
    local B="$((${#times[@]}-2))" 
    for((; b<B; b++)); do
      if ((needle >= times[b] && needle < times[b+1])); then break; fi
    done
  echo "${strings[$b]}"
}

FuzzyTime "$1"

テスト:

$ for t in {0..27}; do FuzzyTime "$t"; done
0 -- why don't you go to bed
1 -- why don't you go to bed
2 -- why don't you go to bed
3 -- why don't you go to bed
4 -- why don't you go to bed
5 -- why don't you go to bed
6 -- I see your very eager to start the day
7 -- I see your very eager to start the day
8 -- I see your very eager to start the day
9 -- I see your very eager to start the day
10 -- and a very good day too you
11 -- and a very good day too you
12 -- and a very good day too you
13 -- Good Afternoon
14 -- Good Afternoon
15 -- Good Afternoon
16 -- Good Afternoon
17 -- Good Afternoon
18 -- Good Afternoon
19 -- Good Evening
20 -- Good Evening
21 -- Good Evening
22 -- it is getting late, it's time to party or go to bed
23 -- it is getting late, it's time to party or go to bed
24 -- guess the planet your on has more than a 24 hour rotation
25 -- guess the planet your on has more than a 24 hour rotation
26 -- guess the planet your on has more than a 24 hour rotation
27 -- guess the planet your on has more than a 24 hour rotation

おすすめ記事