Categories
linux tech

Correct Way To Iterate Over Files In Bash

Because I keep forgetting, here’s a reminder to myself of the correct way to iterate through files and directories in bash, even considering spaces in filenames, whith a hat-tip to Thomas Howard Uphill:

find . -type f|grep .ext$ |while read file
do
/do/something/to "$file"
done

Silly rabbit.

Categories
all posts linux ubuntu

Count Arguments In A Bash Script

Another useful tip I’m sure most people will be familiar with, but in bash scripts $# stores the number of arguments passed to the script. Eg, combine with $@ (all arguments) for batch processing (what I used it for):


foreach $arg in $@; do
[stuff]
[compare with $# to tell remaining items]
done

Very basic stuff, but it was new to me yesterday, and it might save someone a bit of time searching.