Sayuj
Sayuj

Reputation: 7622

Shell script - No such file error

#!/bin/bash
local dept=0
while [ $n < 5 ]
do
  echo $n
  $n++
done

this code returns error 7: cannot open 5: No such file Where should I change?

Upvotes: 0

Views: 1793

Answers (3)

GreyCat
GreyCat

Reputation: 17104

Most portable (POSIX sh-compliant) way is:

#!/bin/sh -ef
n=0
while [ "$n" -lt 5 ]; do
    echo "$n"
    n=$(($n + 1))
done

Note:

  • "$n" - quotes around $n help against crashing with missing operand error, if n is not initialized.
  • [ (AKA test) and -lt - is a safe and fairly portable way to check for simple arithmetic clauses.
  • $((...)) is a safe and portable way to do arithmetic expansion (i.e. running calculations); note $n inside this expansion - while bash would allow you to use just n, the standard and portable way is to use $n.

Upvotes: 1

clt60
clt60

Reputation: 63902

#!/bin/bash
n=0
while [[ "$n" < 5 ]]
do
   echo $n
   ((n++))
done
~  

Upvotes: 1

Alftheo
Alftheo

Reputation: 888

You should use $n -lt 5. Bash reads the < there as redirection, so it tries to open a file named 5 and feed its contents to a command named $n

This works for me:

#!/bin/bash
n=0
while [ $n -lt 5 ]
do
  echo $n
  let n=$n+1
done

Upvotes: 6

Related Questions