Reputation: 809
I am beginner in UNIX. I am getting a silly error while writing a while
loop.
Code:-
$ x=0
$ while [ $x -lt 10 ]
> do
> echo $x
> x=´echo "$x + 1" | bc´
> done;
I am getting the errors:-
0
bc´: command not found
0
bc´: command not found
0
bc´: command not found
...
Can any body help me? I have no idea of shell programming.
Upvotes: 0
Views: 1836
Reputation: 28029
You're not using backticks. Use ` (aka grave accent, aka U+0060) (found in the top-left on American keyboards) instead of ´ (aka acute accent, aka U+00B4).
For example, the following works fine:
x=0
while [ $x -lt 10 ]; do
echo $x
x=`echo "$x + 1" | bc`
done
The only difference between yours and mine are the ticks used to quote echo "$x + 1" | bc
.
That being said, if you happen to be using bash (or a bash-like shell), there are much better ways of making the same loop. For example:
x=0
while (( x++ < 10 )); do
echo $x
done
This has the advantage of being both faster (because it doesn't call to outside programs) and easier to read (because it uses more traditional coding syntax).
Upvotes: 0
Reputation: 5772
If you are doing x=´echo "$x + 1" | bc´
to increment x
(which is wrong as pointed by danf), pls use the following
x=`expr $x + 1`
also note the spaces...bash
is very picky
Here is the output --
xxxx@cse:~> x=5
xxxxx@cse:~> while [ $x -lt 10 ]; do echo $x; x=`expr $x + 1`; done;
5
6
7
8
9
You can use bc
to get this to work, but it is better to use expr
xxxx@cse:~> x=5
xxxx@cse:~> while [ $x -lt 10 ]; do echo $x; x=`echo "$x + 1"|bc`; done;
5
6
7
8
9
Upvotes: 1
Reputation:
Don't use backticks to execute subcommands, use $( cmd )
, this construct can be nested. Maybe you do the arithmetic with a pipe to bc for learning purposes, otherwise, the shell is capable of doing this in a number of ways
$((x+=1))
x=$((x+1))
$((++x))
$((x++))
HTH and kind regards
Upvotes: 0
Reputation: 1002
You seem to have a parse error. You need a backquote. Change line to:
x=`echo "$x + 1" | bc`
Upvotes: 0