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

发布于 2024-09-30 21:38:54 字数 582 浏览 1 评论 0原文

好的,我正在尝试检查文件是否存在,如果存在,则我为用户提供再次下载该文件的选项 - 我希望默认值(输入)为 Y,我希望 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

Ok I'm trying to have a situation where I check if a file exists, if it does then I give the user the option to download it again - I want the default (enter) to be Y, I want Y or y to continue the script, I want N or n to exit the script, and I want all other responses to go back and re-prompt the question... but I'm stuck on that.

What I've done really just continues on (enter), and fails on all other responses other than lowercase y.

Here it is:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄荷梦 2024-10-07 21:38:54

通常使用的结构是 case

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

The usual structure to use for this is case.

case "$decide" in
  y|Y|'') echo "yes" ;;
  n|N) echo "no" ;;
  *) echo "boo" ;;
esac
无可置疑 2024-10-07 21:38:54

尝试使用 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

Try a while loop:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文