Reputation: 10168
#!/bin/bash
if test "$#" == "4"; then echo "$*"; else echo "args-error" >&2; fi;
This little code snippet troubles me a lot when I tried to run it on both Ubuntu and Cygwin.
Ubuntu runs bash version 4.0+ whereas Cygwin runs 3.2.49; But I reckon version collision shall not be the cause of this, this code runs well under fedora 10 which is also using bash version 3.+
So basically I am wondering if there is a way to code my script once and for all so there are not to have this awful issue later on.
Many thanks in advance.
Edited : I don't have Cygwin by hand at the moment but from my memory, it keeps saying something like couldn't resolve undefined token "fi" something like that.
Edited : well,the original form is like this, just found from server :
#!/bin/bash
if ["$#" == "4"];
then echo "$*";
else echo "args-error" >&2;
fi;
Console complains :
$ ./test.sh 1 2 3
./test.sh: line 2: [3: command not found
args-error
I am also wondering how come that stderr says something goes wrong - command not found - but can still print out the answer?
Upvotes: 5
Views: 4979
Reputation: 9488
try to use operator '=' instead of '==' . And also add one space after [
and another before ]
as folowing
if [ "$#" = "4" ];
then echo "$*";
else echo "args-error" >&2;
fi;
Or even try '-eq' instead of '=='
if [ "$#" -eq "4" ];
Because in some systems, it does not accept the operator '=='
Upvotes: 1
Reputation: 126203
In your edit to show the 'original form' the problem would seem to be that you're missing a space between the [
and the "
Upvotes: 2
Reputation: 118605
You need whitespace around the [
and ]
.
#!/bin/bash
if [ "$#" == "4" ];
then echo "$*";
else echo "args-error" >&2;
fi;
Upvotes: 7
Reputation: 838216
Updated answer:
You need a space after [
otherwise ["$#"
is evaluated to for example [3
which doesn't exist. Try this:
if [ "$#" == "4" ];
then echo "$*";
else echo "args-error" >&2;
fi;
It works for me. I would guess that you are getting an error like this:
test.sh: line 2: $'\r': command not found
test.sh: line 3: $'\r': command not found
This can happen because you have edited the file using Windows-style line endings but Bash expects Unix-style line endings. To fix the file, try running this command:
dos2unix test.sh
You of course need to change the filename to the actual filename of your script.
Upvotes: 4