开发者

Shell script - No such file error

#!/bin/bash
lo开发者_开发技巧cal 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?


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


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


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜