0

I am trying to write a shell script that takes an unspecified no. of command line arguments upto 9 and finds their sum. The number should be added to sum only if it is greater than 10. The code that I have tried is

#!/bin/sh
sum=0
for i in $@
do
        if [$i -gt 10]
        then
                sum=$((sum+i))
        else
                continue
        fi
done
echo $sum

But I am getting the following error when I try to execute

xyz@LAPTOP-1NOBF8F8:~$ vi Sum2.sh
xyz@LAPTOP-1NOBF8F8:~$ chmod +x Sum2.sh
xyz@LAPTOP-1NOBF8F8:~$ ./Sum2.sh 19 5 3
./Sum2.sh: 5: [19: not found
./Sum2.sh: 5: [5: not found
./Sum2.sh: 5: [3: not found
0

Please let me know what am I missing .

  • Save yourself some trouble by running your scripts through [shellcheck](https://www.shellcheck.net) – that other guy Mar 22 '21 at 04:45
  • @dishaNasa : You are missing a space. As the error message tells, you, when `i` has the value i.e. 19, `[$i` expands to a command `[19`, and this command does not exist in your PATH. – user1934428 Mar 22 '21 at 11:07

2 Answers2

1

[ is a command so should be separated from surrounding stuff by whitespace(a), as should the ] terminator:

if [ $i -gt 10 ]

See the following transcript for an example:

pax> [4 -gt 3] && echo yes
[4: command not found

pax> [ 4 -gt 3 ] && echo yes
yes

(a) It's no different to expecting ls-al to work without the space between the s and -.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

[ needs to be followed by space (and ] needs to be preceeded by one as well).

weirdan
  • 2,499
  • 23
  • 27