earthbound19 / _ebDev

Various tools, mostly custom-made for art development.
2 stars 2 forks source link

Improve .sh script loops over arrays #20

Closed earthbound19 closed 4 years ago

earthbound19 commented 5 years ago

Replace all mapfile-generated loops (from resultant arrays) in .sh scripts with ifs read loops (which read the last line if no trailing newline at end of input), re: http://stackoverflow.com/a/31398490

while IFS= read -r line || [ -n "$line" ]; do
  echo "$line"
done <file

Or should that be with IFS=' ' ?

~I HAD THOUGHT THE FOLLOWING better, but it breaks down when array elements contain spaces, even if you set IFS="". If you try to iterate over an array with spaces in the elements, it lumps it all into one element:~ UPDATE: Isn't that supposed to be IFS=' ' or IFS=" "` (with a space) though? will that work?

~Or skip creating any files and iterate through an array created in memory (the printf command trims any ./ from the start of output)~ ; re: https://stackoverflow.com/a/12566981/1397555

IFS=" "
array=(`find . -maxdepth 1 -type f -iname \*.$1 -printf '%f\n'`)
# or to find every file,`gfind .` . .
for element in ${array[@]}
do
    echo $element
done

-- which may work with loops that use ffmpeg where file loops that use ffmpeg usually fail on Mac, it seems

earthbound19 commented 4 years ago

This can work:

readarray -d '' array < <(find . -name "*.$1" -print0)

-- from here: https://stackoverflow.com/a/54561526/1397555 -- but so can this; subscriptable; adds stuff that sorts by file date (which I want here):

array=(`find . -name "*.$1" -print0 -printf "%T@ %Tc %p\n" | gsort -n | gsed 's/.*[AM|PM] \.\/\(.*\)/\1/g'`)

echo "${array[4]}"
echo ""

for element in ${array[@]}
do
    echo $element
done
earthbound19 commented 4 years ago

I may not ever get this conversion done with all scripts; if I find any broken, I'll fix it to this end. Meanwhile, I've ported this information into a file documentationHeader.md, which is intended to be put at the start of a DOCUMENTATION.md file generated by makeDocumentation.md. Closing.

earthbound19 commented 3 years ago

An AKTUL best true way to create arrays:

array=( $(find . -maxdepth 1 -type f -iname \*.png -printf '%f\n') )

The outer parenthesis supposedly makes it a true bash array.