0

I was hoping someone could give me a hand. I'm just starting to learn shell scripting in Unix using the Bourne shell and I've run into a problem.

I'm trying to make a script that takes a file with a series of digits and reads through it with a while loop and checks if the number is larger than 30. If it is, it will increment a counter. At the end it echoes how many times there was a number larger than 30.

The file looks similar to this but larger.

0107
0027
0110

and this is my code

#!/bin/sh
count=0
while read p;do
if ["$p" -ge 30 ]
then
 count=`expr $count + 1`
fi
done < $1
echo " has logged in for more than 30 minutes $count times "

In the end I expected this to say you logged in 2 times but instead I get this error for each number in the file. Here is an example.

./scriptname: 4: ./scriptname: [0107: not found

Anyway I was thinking that perhaps it wasn't treating the integers as integers but instead as strings. Maybe I didn't format my "if" properly but I'm not sure what's wrong; that's why I've come here.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2904491
  • 11
  • 1
  • 2
  • Oh dear ive been beating myself up on this for a while and the problem was so silly, thank you so much! – user2904491 Mar 13 '15 at 05:01
  • This is the same problem as caused the trouble in [Bash script — syntax to compare strings as integers](http://stackoverflow.com/questions/29021755/bash-script-syntax-to-compare-strings-as-integers) and a large number of other problems. The command name needs to be kept separate from its arguments, and `[` is a command (it is usually a shell built-in, but there's often also a binary program that implements more or less the same functionality in `/bin/[` or `/usr/bin/[` or both). – Jonathan Leffler Mar 13 '15 at 05:55

2 Answers2

0

You need to add a single space to your if like

if [ "$p" -ge 30 ]

The reasons for this should become clear if you

$ type [

and

$ which [
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You need space after open square bracket like:

if [ "$p" -ge 30 ]
    ^
SMA
  • 36,381
  • 8
  • 49
  • 73