Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
docs:bash:bash_loop [2007/05/14 11:54] billhdocs:bash:bash_loop [2010/05/07 11:19] (current) billh
Line 1: Line 1:
 +====== bash loop ======
  
 +===== while read =====
 +  * :-) This code WILL work on filenames with spaces
 +  * taken from http://www.macgeekery.com/tips/cli/handling_filenames_with_spaces_in_bash
 +  * 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."//<code>
 +ls -1L *.tiff | while read file;do
 +du -h -d 0 "${file}"
 +done
 +</code>
 +  * another example:<code>
 +ls -1L *.tiff | while read file;do
 +tiff2pdf -p letter -o "${file}".pdf "${file}"
 +done
 +</code>
 +  * use a file containing a list of filenames for a copy operation:<code>
 +cat fileswithnotesbug.txt | while read file;do
 +cp "${file}" /cygdrive/n/Receive/CIA/nsf/ClmTest/;
 +done
 +</code>
 +
 +
 +===== for =====
 +  * :!: 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)
 +<code>
 +for file in `ls -1L`;do
 +du -h -d 0 $file
 +done
 +</code>
 +
 +Another example showing how to set up new folders with git repo's:
 +<code>
 +$ mkdir ~/git
 +$ cd ~/git
 +$ for i in a b c d
 +do
 +        mkdir $i
 +        cd $i
 +        git init
 +        echo "module $i" > $i.txt
 +        git add $i.txt
 +        git commit -m "Initial commit, submodule $i"
 +        cd ..
 +done
 +</code>
 +
 +original url: http://www.kernel.org/pub/software/scm/git/docs/user-manual.html#submodules
 +
 +===== other notes =====
 +  * http://www.linuxquestions.org/questions/showthread.php?t=453181
 +<code>
 +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).
 +</code>