ElenaD ElenaD - 7 months ago 19
Bash Question

Bash error: "line 8: [: 2: unary operator expected"

Please help me with this error I received with a shell script in Bash:

line 8: [: 2: unary operator expected


#!/bin/bash

echo "Input your number for factorial calculation: "
read $nr

counter=2
factorial=1

while [ $counter -le $nr ]
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter + 1 ))
done

echo "The result " $nr "! is:"
echo $factorial


Something is wrong with the while line. Maybe the
$nr
is not used correctly?

Answer

read takes name of the variable, not its value. You need to replace read $nr with read nr.