This has me stumped. New to shell scripting and playing around with the ZSH in macOS Catalina (although I think the same thing happens in bash too.)
I have the following script I'm playing around with which I've saved in a file called f
that has no extension. I chmod
'd it with -x
and I put it in my local bin
folder which is in my path variable.
clear
echo "Argument Count: $#"
if [ $# == 0 ]; # Run if no arguments
then
echo "You ran this with no arguments!"
exit 0
fi
if [ $1 == "a" ]; # Run if the first argument is 'a'
then
echo "You ran A!"
exit 0
fi
# Run if nothing matches the above
echo "No matches!"
The above works as I expect. If I type this...
f
I get this...
Argument Count: 0
You ran this with no arguments!
If I type this...
f a
I get this...
Argument Count: 1
You ran A!
And finally, if I type this...
f b (or f c, f foo, etc.)
I get this...
Argument Count: 1
No matches.
Again, works exactly like I would expect.
However, if I change the script to this where I simply comment out the first if
block...
clear
echo "Argument Count: $#"
# if [ $# == 0 ]; # Run if no arguments
# then
# echo "You ran this with no arguments!"
# exit 0
# fi
if [ $1 == "a" ]; # Run if the first argument is 'a'
then
echo "You ran A!"
exit 0
fi
# Run if nothing matches the above
echo "No matches!"
...and I type f
by itself, I now get this!
Argument Count: 0
/Users/[redacted]/bin/f: line 11: [: ==: unary operator expected
No matches!
Note: Line 11 is the one with the comment # Run if the first argument is 'a'
Even more odd is if I type the following, which directly runs the code on line 11 that it's complaining about...
f a
I get this, which works correctly!
Argument Count: 1
You ran A!
So what the heck am I missing here??