How to Use Variables in a Bash for Loop

How to use variables in a bash for loop

One way is using eval:

for i in $( eval echo {0..$length} )
do
echo "do something right $i"
done

Note what happens when you set length=;ls or length=; rm * (don't try the latter though).

safely, using seq:

for i in $( seq 0 $length )
do
echo "do something right $i"
done

or you can use the c-style for loop, which is also safe:

for (( i = 0; i <= $length; i++ )) 
do
echo "do something right $i"
done

How to use variables in a range from 1 to 200 in loop on bash

Brace expansion happens before variable expansion, so you can't use it with variables. Use a loop or the seq command.

for ((i=t1; i<=t2; i++)) ; do
host=$host_start$i.$domain

or

for i in $( seq $t1 $t2 ) ; do
host=$host_start$i.$domain

Store for loop results as a variable in bash

It's really easy, you can just redirect the output of the whole loop to a variable (if you want to use just one variable as stated):

VARIABLE=$(for time in ...; do ...; done)

your example:

var=$(for time in ${seconds_list}; do
echo "scale=2; (${cur_time}-${time})/3600" | bc
done)

Just enclosing your code into $().

Exporting multiple variables in a for loop

This works fine. The variables exported are local and only available until the end of your script. When the script closes they are no longer available in the shell. This is normal.
if you write bash on the last line of your script it will open a new terminal with the exported variables available.



Related Topics



Leave a reply



Submit