This is an old revision of the document!


bash loop

  • :-) This code WILL work on filenames with spaces
  • quote “For splits items on a space, regardless of if they’re quoted (if they’re stored in a variable). However, the read command does not.”
    ls -1L *.tiff | while read file;do
    du -h -d 0 "${file}"
    done
  • another example:
    ls -1L *.tiff | while read file;do
    tiff2pdf -p letter -o "${file}".pdf "${file}"
    done
  • :!: This code will NOT work on filenames with spaces unless the IFS variable is set in bash (see man bash for more details)
  • note that the symbols used are backticks, not single quotes (backtick is the key left of 1)
for file in `ls -1L`;do
du -h -d 0 $file
done
Props to this post, this is a very elegant solution to weird characters in filenames:
http://www.macgeekery.com/tips/cli/h...spaces_in_bash
Code:

find . -type f -print | while read i; do touch "${i}"; done


    That will fail if any filenames have leading or trailing spaces or end in a backslash. (Not to mention filenames containing newlines.)

Quote:
'for' splits on spaces. Period. Regardless of quoting.


    It does not split on spaces if there is no space in the value of $IFS.

Quote:
'read' does not.


    It does if more than one variable is given as an argument (and IFS contains a space).
  • docs/bash/bash_loop.1217744747.txt.gz
  • Last modified: 2010/03/07 13:47
  • (external edit)