Cygwin error when doing if...then...fi - Bash script

I just started bash shell programming. I have installed Cygwin on my Windows 7 computer. I started writing a script using this tutorial. My script requires an argument to be passed to it, if it doesn't it should display an error message. This is the code directly from the tutorial and the same one in my code:

[ $# -eq 0 ] && { echo "usage: someArgument";  exit 1; }

When I do the following:

sh ./myscript.sh

it gives me this error:

-bash: /home/Me/myscript.sh: line 5: syntax error: unexpected end of file

"Unexpected end of file" means I have missed a fi or done, etc. somewhere.

I double-checked my code, but found nothing. Plus, when I comment out the line the script works perfectly fine.

I tried using a if...then...fi:

if [ $# -eq 0 ]
then
    echo "usage: someArgument"
    exit 1;
fi

but to no avail!

Please help, it's been stumping me.

Answers


Probably you have \r or some other invisible symbols in the script. Please add set -x to the beginning of the script to switch debug on and run script once again.


Sorry for the trouble. I did some research on the invisible symbols mentioned by Igor. You have to run dos2unix in Cygwin which solved it for me. Dos-type files have \r\n instead of \n and some other stuff which makes Cygwin confused.

This:

$ dos2unix ./myscript.sh
$ sh ./myscript.sh

works correctly.


As an alternative, you can use bash parameter expansion to test for an unset variable. With no positional parameters, $1 will be unset:

: ${1?"usage: someArgument"}

The : command is a null-op, serving as a hook to expand its argument, which is $1. If $1 is unset, the word following the ? will undergo some expansion and be printed to standard error, after which a non-interactive shell will exit.

(This isn't a solution to your DOS line-ending problem, but just another approach to enforcing that a variable is set.)


Need Your Help

The best way to have a persistent object ready to use

android service broadcastreceiver

maybe there are some similar questions like mine, but after searching for long time i couldn't find any!