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?
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 ==.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With