$ cat fromhere.sh
#!/bin/bash
FROMHERE=10
for i in $(seq $FROMHERE 1)
do
echo $i
done
$ sh fromhere.sh
$
Why doesn't it works?
I can't find any examples searching google for a descending loop..., not even variable in it. Why?
Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables. Bash's += works pretty similar to compound operators in other programming languages, such as Java.
You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.
#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications.
Using + and - Operators The most simple way to increment/decrement a variable is by using the + and - operators. This method allows you increment/decrement the variable by any value you want.
Bash has a for
loop syntax for this purpose. It's not necessary to use the external seq
utility.
#!/bin/bash
FROMHERE=10
for ((i=FROMHERE; i>=1; i--))
do
echo $i
done
You should specify the increment with seq:
seq $FROMHERE -1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With