简体   繁体   中英

Process files recursively using bash

I currently have a small script that processes all files in a directory. I would like this to also recursively process all files in the subfolder. Any thoughts on how to do this? My current code is:

#!/bin/bash
for file in ./input/*
do
   do_something "$file"
done

You can use find :

find input/ -type f -exec do_something {} \;

From the man page:

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the primaries and operands listed below) in terms of each file in the tree.

For clarity, here's some more detail from the man page about exec and {} :

-exec utility [argument ...] ;

True if the program named utility returns a zero value as its exit status.

Optional arguments may be passed to the utility. The expression must be terminated by a semicolon ( ; ). If you invoke find from a shell you may need to quote the semicolon if the shell would otherwise treat it as a control operator. If the string {} appears anywhere in the utility name or the arguments it is replaced by the pathname of the current file. Utility will be executed from the directory from which find was executed. Utility and arguments are not subject to the further expansion of shell patterns and constructs.

Hope this helps :)

In bash 4, you can use the ** pattern, which matches 0 or more directories in a path.

shopt -s globstar
for file in ./input/**/*
do
   do_something "$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