JavaSa
JavaSa

Reputation: 6242

How to use while loop in bash

New to bash I was trying to write simple while loop:

let i = $1
while(i < 4); do
   echo Hi
   ((i++))
   done

Running this with: $ bash bash_file.sh 0
Gave me this warning bash_file.sh line 2: 4: no such file or directory

Question: since when a variable must be file or directory?
How to solve this?

EDIT: if I want to loop while i < $1 + $2, when $1 and $2 are numbers, how to write it>

Upvotes: 5

Views: 9841

Answers (2)

Andrew
Andrew

Reputation: 986

i=$1
while [ "$i" -le 4 ]
do
    echo $i
    i=$((i+1))
done

More about bash conditions: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Looping-Constructs

Upvotes: 5

chepner
chepner

Reputation: 532398

You need an arithmetic statement (two parentheses), not a subshell. let is unnecessary here.

i=$1
while (( i < 4 )); do
...
done

while's argument is a shell command. ( i < 4 ) starts a subshell which runs the command i, reading input from a file named 4. The redirection is processed before the command is looked up, which explains why you don't get a i: command not found error.

You can simply replace 4 with the expression you want to use:

while (( i < $1 + $2 )); do

Upvotes: 5

Related Questions