Bash shell脚本在条件下进行多次测试

时间:2015-04-08 17:29:25

标签: bash while-loop multiple-conditions

首先,是的,我读过这个:

Bash scripting, multiple conditions in while loop

答案可能在那篇文章中,但我没有看到它,所以我希望有人可以提供帮助。我想在我的while循环中测试两个条件,基本上我想结合这两个当前嵌套的测试,一个只是一个正则表达式,第二个是测试它是否实际上是一个有效的日期:

while ! [[ "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]]; do
    read -p "Enter date in format DDmmmYYYY: " searchDate

    while ! (date -d $searchDate); do
        read -p "That date doesn't appear to be valid, try again: " searchDate
    done
done

我觉得我应该能写出类似的内容:

while [[ ! "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]] || ( ! date -d $searchDate); do
    read -p "There's something funky about that date, try again: " searchDate

但是我无法让它发挥作用,我不确定我的逻辑是否是偏斜,或者我试图结合测试的方式(或两者都有!)......

1 个答案:

答案 0 :(得分:2)

你可以做到

while [[ ! "$searchDate" =~ ^[0-9]{1,2}[a-zA-Z]{3}[0-9]{4}$ ]] || ! date -d $searchDate; do
    read -p "Enter date in format DDmmmYYYY: " searchDate
done