Bash脚本帮助if then else和区分大小写

时间:2010-11-06 10:52:31

标签: bash cron if-statement case-sensitive case-insensitive

好的我正试图检查一个文件是否存在,如果确实存在,那么我给用户再次下载它的选项 - 我希望默认(输入)为Y,我想要Y或为了继续脚本,我希望N或n退出脚本,我希望所有其他响应返回并重新提示问题...但我坚持这一点。

我所做的只是继续(输入),并且除了小写y以外的所有其他响应都失败了。

这是:

if [ -f $target/$remote_backup ];then
    read -p "This file already exists, do you still want to download? [Y/n]" decide
     if [ -z $decide ];then
        # if you press return it'll default to Y and continue
        decide="Y"
    else
        if [ $decide != y ]; then
        echo "Ok you said no or pressed a random button, exiting"
        exit -1
    fi
fi
fi

2 个答案:

答案 0 :(得分:4)

通常用于此的结构是case

case "$decide" in
  y|Y|'') echo "yes" ;;
  n|N) echo "no" ;;
  *) echo "boo" ;;
esac

答案 1 :(得分:1)

尝试while循环:

if [ -f $target/$remote_backup ]; then
    decide="?"
    while [ "$decide" != "y" -a "$decide" != "n" ]; do
        read -p "This file already exists, do you still want to download? [Y/n] " decide
        if [ -z $decide ]; then
            decide="y"
        fi
    done
    echo Decision: $decide
fi