Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using test command in if statement

Tags:

linux

bash

I am trying to create an if statement using the test command that checks if the variable "name" contains "Scott Pearce".

#!/bin/bash

name="Scott Pearce"
if test $name == "Scott Pearce";
then
      echo "Yes"
else
      echo "No"
fi

When I run the script I get an error saying :

./script1: line 5: test: too many arguments

Any idea what I am doing wrong?

like image 548
Scott Pearce Avatar asked Mar 13 '26 15:03

Scott Pearce


2 Answers

if test "$name" = "Scott Pearce";

You need to quote the variable, otherwise when the shell expands it, test will not get the right number of arguments since your variable contains a space.

Also the string equality operator for test is =, not ==.

like image 193
Mat Avatar answered Mar 16 '26 04:03

Mat


If you really want to test contains, then pick one of

bash

if [[ $name == *"Scott Pearce"* ]]; then ...    

POSIX

case "$name" in
    *"Scott Pearce"*) echo Hi Scott ;;
    *) echo Begone stranger ;;
esac

The == operator in bash's [[ command is a pattern matching operator.

like image 44
glenn jackman Avatar answered Mar 16 '26 05:03

glenn jackman