bash script read all the files in directory

后端 未结 3 762
花落未央
花落未央 2021-02-02 07:36

How do I loop through a directory? I know there is for f in /var/files;do echo $f;done; The problem with that is it will spit out all the files inside the directory

相关标签:
3条回答
  • 2021-02-02 08:05

    A simple loop should be working:

    for file in /var/*
    do
        #whatever you need with "$file"
    done
    

    See bash filename expansion

    0 讨论(0)
  • 2021-02-02 08:23

    You can go without the loop:

    find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 
    

    HTH

    0 讨论(0)
  • 2021-02-02 08:27

    To write it with a while loop you can do:

    ls -f /var | while read -r file; do cmd $file; done
    

    The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

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