gpt4 book ai didi

bash - 是/否导致 "==Yes"循环的 shell 脚本?

转载 作者:行者123 更新时间:2023-12-04 19:00:03 25 4
gpt4 key购买 nike

我正在创建一个 shell 脚本来自动执行 sudo apt update/upgrade/autoremove/autoclean (我生命中的第一个 bash 脚本),一切正常,但是或否部分

这是我的代码:

#!/bin/bash
echo "Updating and upgrading system components"
sudo apt update
sudo apt upgrade
echo "Starting cleaning and removing unnecessary files"
sudo apt autoremove
sudo apt autoclean
echo "Do you want to check if a new distribution update is available? Y/N"
read -p "Check system distribution updates?" answer
if ["$answer" == "Y" || "$answer" == "Yes" || "$answer" == "y" || "$answer" == "yes"]
then
sudo do-release-upgrade
else
exit
fi

回答这些选项之一后,shell 开始循环打印“==Yes”

任何想法?

最佳答案

[需要用空格与其参数分开。 ["$answer"被解析为带有两个参数的单个命令,==Y .这样的命令不存在,所以它失败了,||尝试下一个命令。下一个命令是 yes :这是一个无限打印其参数的命令。本例中的参数是 ==Yes .

写条件的正确方法是

if [ "$answer" == "Y" ] || [ "$answer" == "Yes" ] || [ "$answer" == "y" ] || [ "$answer" == "yes" ]

或者
if [ "$answer" == "Y" -o "$answer" == "Yes" -o "$answer" == "y" -o "$answer" == "yes" ]

或者,如果您使用的是 bash
if [[ $answer == Y || $answer == Yes || $answer == y || $answer == yes ]]

您还可以使用参数扩展来小写答案(但它包括 yEs 等在接受的答案中)
if [[ ${answer,} == y || ${answer,,} == yes ]]

或者您可以使用带有 =~ 的正则表达式运算符(operator)
if [[ ${answer,,} =~ ^y(es)?$ ]]

shopt -s extglob 下,您可以使用一种模式在一个表达式中匹配这两种情况:
if [[ ${answer,,} == y?(es) ]]

关于bash - 是/否导致 "==Yes"循环的 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60791757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com