简体   繁体   中英

bash: processing (recursively) through all files in a directory

I want to write a bash script that (recursively) processes all files of a certain type.

I know I can get the matching file list by using find thusly:

find . -name "*.ext"

I want to use this in a script:

  1. recursively obatin list of files with a given extension
  2. obtain the full file pathname
  3. pass the full pathname to another script
  4. Check the return code from the script. If non zero, log the name of the file that could not be processed.

My first attempt looks (pseudocode) like this:

ROOT_DIR = ~/work/projects
cd $ROOT_DIR
for f in `find . -name "*.ext"`
do
    #need to lop off leading './' from filename, but I havent worked out how to use
    #cut yet
    newname = `echo $f | cut -c 3
    filename = "$ROOT_DIR/$newname"

    retcode = ./some_other_script $filename

    if $retcode ne 0
       logError("Failed to process file: $filename")
done

This is my first attempt at writing a bash script, so the snippet above is not likely to run. Hopefully though, the logic of what I'm trying to do is clear enough, and someone can show how to join the dots and convert the pseudocode above into a working script.

I am running on Ubuntu

find . -name '*.ext' \( -exec ./some_other_script "$PWD"/{} \; -o -print \)

Using | while read | while read to iterate over file names is fine as long as there are no files with carrier return to be processed:

find . -name '*.ext' | while IFS=$'\n' read -r FILE; do
  process "$(readlink -f "$FILE")" || echo "error processing: $FILE"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM