framilano
framilano

Reputation: 101

Yes/No shell script causing "==Yes" loop?

I'm creating a shell script to automatically do sudo apt update/upgrade/autoremove/autoclean (first bash script of my life), everything works but the yes or no section

Here's my code:

#!/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

After answering one of these option shell starts printing in loop "==Yes"

Any idea?

Upvotes: 0

Views: 186

Answers (1)

choroba
choroba

Reputation: 242343

[ needs to be separated by space from its arguments. ["$answer" gets parsed as a single command with two arguments, == and Y. Such a command doesn't exist, so it fails, and || tries the next command. The next command is yes: it's a command that prints its arguments infinitely. The arguments in this case are == and Yes.

The correct way to write the condition is

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

or

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

or, if you're using bash

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

You can also use parameter expansion to lowercase the answer (but it includes yEs etc. among the accepted answers)

if [[ ${answer,} == y || ${answer,,} == yes ]]

Or you can use a regex with the =~ operator

if [[ ${answer,,} =~ ^y(es)?$ ]]

Under shopt -s extglob, you can use a pattern to match both the cases in one expression:

if [[ ${answer,,} == y?(es) ]]

Upvotes: 2

Related Questions