Bash Shell list files using "for" loop
If you're using bash 4, just use a glob:
#!/bin/bash shopt -s globstarfor file in **/*.txtdo if [[ ! -f "$file" ]] then continue fi echo "$file" # Do something else. done
Be sure to quote "$file"
or you'll have the same problem elsewhere. **
will recursively match files and directories if you have enabled globstar
.
Yes, have find
separate the file names with NUL and use read
to delimit on NUL
. This will successfully iterate over any file name since NUL is not a valid character for a file name.
#!/bin/bashwhile IFS= read -r -d '' file; do echo "$file" # Do something else.done < <(find . -type f -name "*.txt" -print0)
Alternatively, if the # do something else
is not too complex, you can use find
's -exec
option and not have to worry about proper delimiting