`end of file' unexpected error

When I am executing my really simple shell script below, I got an error:
`end of file' unexpected. Script is suppose to print out a list of supplied parameters.
Here is my script:

#!/bin/sh

a=$#    #number or parameters
b=0      #starting counter

while [ $a > $b ]
do
   b=`expr $b + 1`
   echo $b
   echo "Parameter is $[$b]"
done

Hi.

I don't get the same error as you.

> is used for redirection.

Try changing the while [$a > $b ] line to while [ $a -gt $b ]

$ ./MyTtest a b c
1
Parameter is $[1]
2
Parameter is $[2]
3
Parameter is $[3]

With your code:

$ ./MyTest a b c
1
Parameter is $[1]
./MyTest: line 6: 1: Is a directory

I would also change b=`expr $b + 1` to b=$((b + 1)) - I'm not much fond of the expr command!

The script as posted prints the message in an infinite loop incrementing $b.

If you just want to print the supplied parameters:

#!/bin/sh
echo "$*"

I finally opened file in vi and noticed that it has a banch of characters:

^M

What is a quick way to clean it?

This is because you edited/created in a Windows environment and every row has a Line Feed and a CR.

The command to remove this is:

dos2unix <FileName>

Just one more comment, if you want the opposite, you have:

unix2dos <FileName>
1 Like

try:

#!/bin/sh

#a=$#    #number or parameters
b=0      #starting counter

while [ $# -gt $b ]
do
   b=`expr $b + 1`
   echo $b
   echo "Parameter is $[$b]"
done
1 Like

john1212 -

while [ $# > $b ]

is incorrect. as scottn already stated > is a redirection operator. use -gt.

1 Like

Modified version of the script to process the input parameters in order:
Notice the use of "shift" to cause each parameter in turn to be called $1 .

#!/bin/sh

a=$#    #number or parameters
b=0      #starting counter

while [ $a -gt $b ]
do
   b=`expr $b + 1`
   echo "Parameter $b is $1"
   shift
done

./scriptname a b c
Parameter 1 is a
Parameter 2 is b
Parameter 3 is c

I just learned that I also could use getopts.:slight_smile:

"getopts" is a good solution. It relies on a structured command line which follows normal unix syntax. No problem with that.
Each parameter starts with a hyphen character and can have an optional parameter value.

e.g. A script with two parameters called "-v" and "-z". The parameter "-v" has a value of "myvalue". The parameter "-z" does not have an associated value.

myscript -v myvalue -z