Bash file while loop isnt running well

I am using the Ubuntu terminal emulator for Windows 10 to try learn the Linux terminal.

I have this code:

cat > c1.sh
echo Give me your name!
read name
echo How many times do you want your laptop to print out your name?
read numberOfLoops
i=0
while [ $i -lt $numberOfLoops ]
do
echo $name
i=$i+1
done
#end

I create the executable file and begin running it:

./c1.sh
 Give me your name!
 Root
 How many times do you want your laptop to print out your name?
 3
 Root
 ./c1.sh: line 6: [: 0+1: integer expression expected

It prints out the name Root "once" as it should but then it stops running and prints out the message ./c1.sh: line 6: [: 0+1: integer expression expected. However if there was a issue with the while loop then it wouldn’t print out the first time Root but it does so I’m not sure what is going on here.

Asked By: Root Groves

||

This is not numeric addition:

i=$i+1

It’s string concatenation. If $i is 0, after the assignment it’s 0+1.

This is numeric addition in bash:

((i=i+1))

or shorter

((++i))
Answered By: choroba

Although syntactically valid, the expression i=$i+1 is a string assignment, so that the second time through the loop you are comparing literal string 0+1 to an integer $numberOfLoops

To get arithmetic evaluation, you can use let i=$i+1, i=$((i+1)) or (in bash – for which you should add a #!/bin/bash shebang at the top of your script, ((i=i+1)) or even ((i++))

If you are really using bash (rather than sh) it would probably be more idiomatic to use a C-style for loop:

#!/bin/bash

read -r -p 'Give me your name! ' name
read -r -p 'How many times do you want your laptop to print out your name? ' numberOfLoops

for ((i=0; i<numberOfLoops; i++)); do
  printf '%sn' "$name"
done

See also the Arithmetic Evaluation section of the bash manual.

Answered By: steeldriver
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.