Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

descending loop with variable bash

Tags:

bash

$ 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?

like image 933
LanceBaynes Avatar asked Jan 13 '11 10:01

LanceBaynes


People also ask

Can you do += in bash?

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.

How do I iterate over a range of numbers defined by variables in bash?

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.

What does #$ mean in bash?

#$ 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.

How do you increment a variable in a bash script?

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.


2 Answers

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
like image 117
Dennis Williamson Avatar answered Oct 20 '22 05:10

Dennis Williamson


You should specify the increment with seq:

seq $FROMHERE -1 1
like image 42
Roy Avatar answered Oct 20 '22 05:10

Roy