Example: Bash Loops

280 words · 2 min read

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
## 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
## article_introduction_to_association_rules_in_r_by_yosuke_yasuda.Rmd
## cssgrid.Rmd
## ddl_to_data.Rmd
## debug_bugs.Rmd
## debug_datatable_bracket_in_own_package.Rmd
## debug_r_isna_all_checks_column_inside_dplyr_mutate.Rmd
## ecmascript_modules.Rmd
## ex_bash_array.Rmd
## ex_bash_loop.Rmd
## ex_jq.Rmd
## ex_r_rmarkdown.Rmd
## ex_r_time_date.Rmd
## ex_sql_data_generator_datafiller.Rmd
## ex_viml_file_expansion.Rmd
## import_js_files.Rmd
## mockup_rest_api_jsonserver.Rmd
## mongodb_import_export_dump_restore_commands.Rmd
## rdb_to_data.Rmd
## rdb_to_ddl.Rmd
## read_json.Rmd
## refcard_css_selectors.Rmd
## refcard_datapasta.Rmd
## refcard_loops.Rmd
## study_frisby_book_adequate_guide_to_fp.Rmd
## study_frisby_flickr_app.Rmd
## study_http_requests_in_js.Rmd
## study_http_requests_in_nodejs.Rmd
## study_hyperapp.Rmd
## study_js_promises.Rmd
## study_notes_cyclejs.Rmd
## study_parcel_jquery.Rmd
## study_parceljs.Rmd
## study_postgrest_starter_kit.Rmd
## study_ramda.Rmd
## using_js_in_rmd.Rmd
## vim_ex_fzf_fuzzy_file_finder.Rmd
## what_is_rdb.Rmd
## yuml_to_data_process.Rmd
## yuml_to_rdb.Rmd
## yuml_to_uml.Rmd

Loop over a range of numbers

for i in {1..5}; do echo $i; done
## 1
## 2
## 3
## 4
## 5

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
## 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}
## {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
## 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
## row: 1
## row: 2

 Tech    13 Dec, 2017

Any work (images, writings, presentations, ideas or whatever) which I own is always provided under
Creative Commons License Creative Commons Attribution-Share Alike 3.0 License

Mert Nuhoglu is a Trabzon-born programmer and data scientist.

You may also like...