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, ifn
is not initialized.[
(AKAtest
) 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 justn
, the standard and portable way is to use$n
.
精彩评论