Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this bash script with `while [expr]` won't run?

Tags:

bash

fibonacci

When I try to run the script I get a "line 9: [2: command not found" error. This is my first bash script so I'm a complete beginner.

#!/bin/bash

num1=0
num2=1

count=2


while [$count -le $1]
do
num3='expr $num1+$num2'
num1=$num2
num2=$num3
count='expr $count+1'

done

echo "Fib Num: $num3"
like image 528
user2012751 Avatar asked Apr 21 '26 00:04

user2012751


1 Answers

Add spaces around the [ and ]. [ is a command, so it has to be a separate word. From man bash:

test expr
[ expr ]
       Return a status of 0 or 1 depending on  the  evaluation  of  the
       conditional  expression expr.  Each operator and operand must be
       a separate argument.  Expressions are composed of the  primaries
       described  above  under  CONDITIONAL EXPRESSIONS.
like image 72
Lev Levitsky Avatar answered Apr 22 '26 17:04

Lev Levitsky