i'm currently working on a small piece of script in bash. As a beginner I can't find a solution to a little problem. I need to do a chrono which decreases with each iteration, but when it's equal to 0, it goes back to 10 (10 -> 0 then 0 -> 10). I wrote a small piece that currently doesn't work.
chrono=5
incremant=-1
while [ $chrono -ge 0 ];
do
echo $chrono
chrono=$((chrono+$incremant))
if [ $chrono -eq 1 ];
then
[ $incremant=1 ];
fi
done
I know it's a really simple problem but I'm really stuck at it. Thank you in advance, have a nice day.
Not sure why you're complicating things with manual loops when bash
has perfecly good C-like loops built in:
fn() {
echo $1
#printf "%2d * %2d = %3d\n" $chrono $chrono $((chrono * chrono))
}
for ((chrono=10; chrono > 0; chrono--)); do fn $chrono ; done
for ((chrono=1; chrono <= 10; chrono++)); do fn $chrono ; done
You can just change the loop sections depending on what you actually need, the current one counts ten to one inclusive then one to ten inclusive, so duplicates 1
. For example, if you don't want the duplicate, just change the first section of the second loop to chrono=2
.
You can also perform arbitrarily complex operations on the value with the fn
function (such as the commented-out bit which gives you a nicely formatted list of expressions giving the square of each number, like 10 * 10 = 100
). The current function just echoes the value:
10
9
8
7
6
5
4
3
2
1
1
2
3
4
5
6
7
8
9
10