Example: Bash Loops
My study notes and examples to remember how to loop in bash.
Table of Contents
Read csv: loop over rows, then parse columns
csv_file=./data/bash_sample_csv.csv
while IFS=, read col1 col2
do
echo "$col1 $col2"
done < $csv_file
## col1 col2
## row11 row12
## row21 row22
IFS
: field separator. Default value: space
Loop over file names matching a pattern
for filename in *.Rmd; do
echo $filename
done
## ex_bash_loop.Rmd
Loop over a range of numbers
for i in {1..5}; do echo $i; done
Loop using variables for end points
Read: https://stackoverflow.com/questions/6191146/variables-in-bash-seq-replacement-1-10#6191382
Using seq
command:
END=2
for i in $(seq 1 $END); do echo "row: $i"; done
## row: 1
## row: 2
The following doesn’t work because brace expansion happens before variable expansion:
start=1
end=10
echo {$start..$end}
## Ouput: {1..10}
Using eval
to make variable expansion first:
END=2
for i in $(eval echo 1 $END); do echo "row: $i"; done
## row: 1
## row: 2
Using arithmetic for loop:
start=1
end=2
for ((i=start; i<=end; i++))
do
echo "row: $i"
done
## row: 1
## row: 2