View Full Version : while with "lesser than" not working
lyngeled
December 21st, 2010, 11:17 PM
Hi, I am trying an "while" with "lesser than" or "greater than" but this example I have found do not work, what's wrong?: #!/bin/bash num=1 while [$num -lt 5]; do num=$[$num + 1]; echo $num; done Regards Lars
unknownPoster
December 21st, 2010, 11:30 PM
it's standard practice on this forum to surround your code with the code tags. Just for readability, I assume this is your program/script:
#!/bin/bash
num=1
while [$num -lt 5];
do num=$[$num + 1];
echo $num;
done
r-senior
December 21st, 2010, 11:40 PM
Don't forget Bash is not as lenient with spacing as a typical programming language. The spaces inside the square brackets (and indeed the lack of spaces in the assignment) are significant.
$ cat test.sh
#!/bin/bash
n=1
while [ $n -le 5 ]; do
echo $((n++))
done
$ ./test.sh
1
2
3
4
5
What error message did you get?
lyngeled
December 22nd, 2010, 02:54 PM
Ok - that worked. Thanks!
I will continue on my script...
Lars
psusi
December 22nd, 2010, 03:41 PM
$[$num + 1] is nonsense, you want $(($num + 1)).
MadCow108
December 22nd, 2010, 04:57 PM
$[$num + 1] is nonsense, you want $(($num + 1)).
its not nonsense, its just less portable.
For bash it works fine but it will fail in dash.
psusi
December 22nd, 2010, 05:48 PM
its not nonsense, its just less portable.
For bash it works fine but it will fail in dash.
Weird. I can't find any reference to $[ in the bash manual, but it does seem to work.
hakermania
December 22nd, 2010, 06:01 PM
Please mark the thread as Solved.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.