Looping through directories in Bash

后端 未结 3 835
名媛妹妹
名媛妹妹 2020-12-24 08:26

I require the script to cd to a directory, then delete all but a few files in sub-directories—but leave the folders alone. Would it help to use switch

相关标签:
3条回答
  • 2020-12-24 09:00

    Using find? You can use several parameters, including depth, file age (as in stat), perms etc...

    find . -maxdepth 2
    
    0 讨论(0)
  • 2020-12-24 09:20

    How about this?

    $ find /Users/YourName/Desktop/Test -type f -maxdepth 2 -not -name watch.log -delete
    


    Explanation

    • -type: look for files only
    • -maxdepth: go down two levels at most
    • -not -name (combo): exclude watch.log from the search
    • -delete: deletes files


    Recommendation

    Try out the above command without the -delete flag first. That will print out a list of files that would have been deleted.

    Once you’re happy with the list, add -delete back to the command.

    0 讨论(0)
  • 2020-12-24 09:25

    You should use find :

    for i in $(find . -type d)
    do
        do_stuff "$i"
    done
    

    If you really have a lot of directories, you can pipe the output of find into a while read loop, but it makes coding harder as the loop is in another process.

    About spaces, be sure to quote the variable containing the directory name. That should allow you to handle directories with spaces in their names fine.

    0 讨论(0)
提交回复
热议问题