Recursively read folders and executes command on each of them

后端 未结 7 1633
执笔经年
执笔经年 2020-12-12 21:05

I am trying to recurse into folders and then run commands on them, using bash script. Any suggestions?

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 21:40

    If you want to recurse into directories, executing a command on each file found in those, I would use the find command, instead of writing anything using shell-script, I think.

    That command can receive lots of parameters, like type to filter the types of files returned, or exec to execute a command on each result.


    For instance, to find directories that are under the one I'm currently in :

    find . -type d -exec echo "Hello, '{}'" \;
    

    Which will get me somehthing like :

    Hello, '.'
    Hello, './.libs'
    Hello, './include'
    Hello, './autom4te.cache'
    Hello, './build'
    Hello, './modules'
    


    Same to find the files under the current directory :

    find . -type f -exec echo "Hello, '{}'" \;
    

    which will get me something like this :

    Hello, './config.guess'
    Hello, './config.sub'
    Hello, './.libs/memcache_session.o'
    Hello, './.libs/memcache_standard_hash.o'
    Hello, './.libs/memcache_consistent_hash.o'
    Hello, './.libs/memcache.so'
    Hello, './.libs/memcache.lai'
    Hello, './.libs/memcache.o'
    Hello, './.libs/memcache_queue.o'
    Hello, './install-sh'
    Hello, './config.h.in'
    Hello, './php_memcache.h'
    ...
    


    Some would say "it's not shell"... But why re-invent the wheel ?
    (And, in a way, it is shell ^^ )


    For more informations, you can take a look at :

    • man find
    • lots of tutorials found with google, like, for instance, Unix Find Command Tutorial

提交回复
热议问题