0

I am trying to write a program that checks whether the number stored in a file (variable n) + 8 is greater or equal to 100. If it is, terminate, else, add 8 and store back in file. However, when I try running it, it says the command in line 4 (if condition) cannot be found. Can someone please explain to me why this isn't working? Thanks.

#!/bin/bash
n=$(cat test.txt)
if [$(($n+8)) -ge 100]
then
    echo 'terminated program' > test.txt
else
    m=$(($n+3))
    echo $m > test.txt
fi
M.Ahmed
  • 11
  • 4

1 Answers1

3

You miss some spaces :

if [$(($n+8)) -ge 100]

->

if [ $(($n+8)) -ge 100 ]

But while using , prefer a modern solution, using bash arithmetic :

if (( n+8 >= 100 ))

or even

if ((n+8>=100))

Like @Gordon Davisson said in comments : arithmetic contexts like inside (( )) are one of the few places in bash where spaces aren't critical delimiters.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Thanks! forgot spacing matters in bash. – M.Ahmed Mar 08 '18 at 22:02
  • Right. `[` is actually a **command**. See `help [` at a bash prompt. And like any command, it needs spaces to separate it from its arguments. Keep in mind that the next word after `if` is a command. – glenn jackman Mar 08 '18 at 22:10
  • 1
    Note: arithmetic contexts like inside `(( ))` are one of the few places in bash where spaces aren't critical delimiters. – Gordon Davisson Mar 08 '18 at 22:55