Difference between revisions of "Bash for loop"

From thelinuxwiki
Jump to: navigation, search
(C style for variable usage)
 
(7 intermediate revisions by one user not shown)
Line 5: Line 5:
 
   done
 
   done
  
 +
using variable start and end parameters
 +
 +
<source lang="bash">
 +
NUM=10
 +
for (( i=2; i<=$NUM; i++ ))
 +
  do
 +
    printf "$i "
 +
  done
 +
</source>
 +
output
 +
<br>2 3 4 5 6 7 8 9 10
  
 
== portable for loop (for older bash versions) ==
 
== portable for loop (for older bash versions) ==
Line 14: Line 25:
 
  for VARIABLE in 1 2 3 4 5 .. N
 
  for VARIABLE in 1 2 3 4 5 .. N
 
  do
 
  do
command1
+
  command1
command2
+
  command2
commandN
+
  commandN
 
  done
 
  done
  
Line 23: Line 34:
 
  for VARIABLE in file1 file2 file3
 
  for VARIABLE in file1 file2 file3
 
  do
 
  do
command1 on $VARIABLE
+
  command1 on $VARIABLE
command2
+
  command2
commandN
+
  commandN
 
  done
 
  done
  
Line 32: Line 43:
 
  for OUTPUT in $(Linux-Or-Unix-Command-Here)
 
  for OUTPUT in $(Linux-Or-Unix-Command-Here)
 
  do
 
  do
command1 on $OUTPUT
+
  command1 on $OUTPUT
command2 on $OUTPUT
+
  command2 on $OUTPUT
commandN
+
  commandN
 
  done
 
  done
+
 
 +
== C style for variable usage==
 +
 
 +
<source lang="bash">
 +
for (( i=0; i<=$length; i++ ))
 +
  do
 +
      echo "do something right $i"
 +
  done
 +
</source>
 
[[category:bash]]
 
[[category:bash]]

Latest revision as of 14:13, 30 August 2021

Example:

 for i in {1..5}
 do
   echo "Welcome $i times"
 done

using variable start and end parameters

 
NUM=10
for (( i=2; i<=$NUM; i++ ))
  do 
    printf "$i "
  done

output
2 3 4 5 6 7 8 9 10

portable for loop (for older bash versions)

for i in `seq 10`
do
   echo "the i is $i"
done
for VARIABLE in 1 2 3 4 5 .. N
do
  command1
  command2
  commandN
done

OR

for VARIABLE in file1 file2 file3
do
  command1 on $VARIABLE
  command2
  commandN
done

OR

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
  command1 on $OUTPUT
  command2 on $OUTPUT
  commandN
done

C style for variable usage

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