Search code examples
bashunixcommand-line-interfacefile-manipulation

Recursively loop through files in bash and manipulate each file through a command


I want to recursively loop through each file in a folder from bash and do some sort of SIMPLE manipulation to them. For example, change permission, change timestamp, resize image with ImageMagick, etc., you get the idea.

I know (like most beginners) on how to do it in a directory, but recursively... ?

$ for f in *.jpg ; do convert $f -scale 25% resized/$f ; done

Let's just keep it simple. say,

$ for f in *; do touch $f; done

Solution

  • Use globstar:

    shopt -s globstar
    for f in ./**; do
        touch "$f"
    done
    

    From the Bash manual:

    globstar

    If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

    BTW, always quote your variables, and use ./ in case of filenames that look like options.

    This is based on codeforester's answer here