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
How to Control a User Systemd Using 'Systemctl --User' After Sudo Su - Myuser
Bash: Difference Between "Export K=1" VS. "K=1"
How to Check If Hadoop Daemons Are Running
Possible to Use a .Dll on Linux
Gzip Multiple Files Individually and Keep the Original Files
Amazon Ec2 - Apache Server Restart Issue
How to Exclude a Folder When Performing File Operations I.E. Cp, Mv, Rm and Chown etc. in Linux
How to Write and Execute a Hello World Program in File for R
Gedit Syntax Highlighting for Assembler Files (*.Asm)
Link a Static Library to a Shared One During Build
Define Alias That References Other Aliases
How to Make Debian Package Install Dependencies
How to Fix Permission Denied for .Git/ Directory When Performing Git Push
How to Convert String to Number in Gnuplot
How to Write Linux Driver Module Call/Use Another Driver Module