while loop not printing correct counter code
Hey Guys,
I'm having an issue with my code here: Code:
#!/bin/bash The execution runtime for i+1 iteration for batchsize of is 5 Whereas what I want is The execution runtime for 1 iteration for batchsize of is 5 The execution runtime for 2 iteration for batchsize of is 5 so on and so forth... Any direction would be sincerely appreciated Guys. |
I think you want ${batchsize} or $batchsize instead of $(batchsize).
Personally I prefer to put all environment variables in ${} for use in strings just for emphasis as it prevents such accidents. |
Also, to increment your counter in bash it would be done with arithmetic expansion
Code:
i=$(($i+1)); |
Quote:
i=$(($i+1)) Too late... |
Super good Guys, Working. But I just don't want solution. Tell me why i=$(($i+1)) is working ? Good tip to use {} for variable. Implemented it.
|
The lame, unsatisfying response is that it is that way just "because" That's what POSIX has to say about how it's written:
http://pubs.opengroup.org/onlinepubs...l#tag_18_06_04 and POSIX is the standard. The $( ) by itself is command substitution and any programs run inside are treated as if they were static text, so that might have something to do with it. |
i suck at memorizing syntax so i do it the long way:
Code:
i=`expr $i + 1` |
All languages have grammar or syntax rules and actually Bash as several ways that an arithmetic expression can be evaluated. The (( )) is compound command and basically equivalent to the let.
i=0 let i=$i+1 declare -i a a=$i+1 https://www.gnu.org/software/bash/ma...rithmetic.html http://wiki.bash-hackers.org/syntax/basicgrammar |
You can also perform the whole task inside the brackets and then your original code would have worked ;)
Code:
(( i = i + 1 )) Code:
(( i++ )) |
And
Code:
((i+=1)) |
or
Code:
((++var)) or ((var=var+1)) or ((var+=1)) Code:
var=0 Code:
userx@voided1.what~>> i=0 We get this: Code:
userx@voided1.what~>> i=0 Saves a lot of, "Why is that not working?" When you run your script thinking it's going to work. |
All times are GMT -5. The time now is 09:11 AM. |