-1

When the variable $favSport is passed in this script to the if statement it works unless the variable contains 2 words

Hi all my son is teaching himself to program (I am technical but not a programmer). He is using bash scripts to learn the concepts of variables and loops. He is 6 so sorry if this code/problem is simple in nature.

He is doing OK and was quite proud of himself but big sisters being big sisters has managed to break his new toy and found a bug in his program he can't figure out. When the script runs and the user gets to the favourite sport section if the variable is 2 words

read -p "So $name what is your favourite sport? " favSport

if [ $favSport == football ] || [ $favSport == soccer ] || [ $favSport == Football ] || [ $favSport == Soccer ]
then
    echo
    echo I like $favSport too!!

else 
    echo
    echo Oh I do not like $favSport. My favourite sport is football.
fi
error line 31: [: too many arguments

occurs but the program continues after that. Line 31 is the if statement

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Possible duplicate of [Meaning of "\[: too many arguments" error from if \[\] (square brackets)](https://stackoverflow.com/questions/13781216/meaning-of-too-many-arguments-error-from-if-square-brackets). While typing a question, StackOverflow shows a list of "similar questions". Please pay attention to these; quite often you can find an answer that way without ever having to actually post the question. – DevSolar Aug 09 '19 at 08:39
  • For future reference, you can try this website to check if your script contains any obvious errors: https://www.shellcheck.net/ – anishsane Aug 09 '19 at 09:52

1 Answers1

2

The issue is due to word splitting. Adding double quotes to $favSport will fix the issue.

if [ "$favSport" == "football" ] || [ "$favSport" == "soccer" ] || [ "$favSport" == "Football" ] || [ "$favSport" == "Soccer" ]

if you didn't give " ", the $favSport will expand to two words (if your input is two words). That is why you are getting too many arguments error. If is expecting a single argument but your variable is split into multiple arguments. Adding a quote wont split the contents in $favSport and solves the issue.

Read this for more about quoting the variables.

j23
  • 3,139
  • 1
  • 6
  • 13