我正在使用bash腳本,但我無法弄清爲什麼我會看到某種行爲。爲什麼bash在爲數組的一部分搜索數組時返回true?
我宣佈月份名稱的數組,像這樣:
declare -a months=("january" "february" "march" "april" "may" "june" "july" "august" "september" "october" "november" "december")
然後,我有一個循環,提示了一個月用戶輸入。如果他們輸入的月份是無效的,那麼它會繼續提醒他們一個月。循環如下所示:
month=
while [[ -z ${month} ]]
do
echo -e "\nPlease enter a month, for example, \"November\"."
read month
if [[ ! "${months[*]}" =~ "${month,,}" ]] ; then
echo -e "\nInvalid month; please check your spelling and try again."
month=
fi
done
如果輸入的字符串與「months」中的條目完全無關,則可以使用該功能。例如,如果我輸入「septiembre」,程序將按預期工作。
但是,如果我輸入一個月份字符串的一部分,例如「nov」或「mber」,程序會將其視爲有效並繼續。
爲什麼當用戶輸入的輸入匹配數組中的一部分字符串時,bash會返回true?爲什麼看不到這些字符串是100%匹配的?
這樣做了;我使用的是bash 4.1,你的建議完美運行。謝謝! – 2014-10-16 20:09:25