5

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>

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

let is unnecessary here. You are using let... (( i < 4 ))
@ikegami: Great, now if I want to loop while i < $1 + $2, when $1 and $2 are numbers
The let i=$1 is unnecessary; ((...)) is basically the same as let, but as a distinct syntactic structure it can be parsed differently (no need to quote * or whitespace, for instance).
5
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.