Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Debian GNU/Linux Reference Guide
Prev Home Next

8.6.19 Script snippets for looping over each file

The following ways of looping over each file matching *.ext ensures proper handling of funny file names such as ones with spaces and performs equivalent process:

  • Shell loop (This example is multi line style with PS2=" " . To do the same in one line, you insert a semicolon for each line break.):

         for x in *.ext; do
           if test -f "$x"; then
             command "$x"
           fi
         done
    
  • find and xargs combination:

         find . -type f -maxdepth 1 -name '*.ext' -print0 | \
          xargs -0 -n 1 command
    
  • find with -exec option with a command:

         find . -type f -maxdepth 1 -name '*.ext' \
          -exec command '{}' \;
    
  • find with -exec option with a short shell script:

         find . -type f -maxdepth 1 -name '*.ext' \
          -exec sh -c "command '{}' && echo 'successful'" \;
    

Debian GNU/Linux Reference Guide
Prev Home Next

 
 
  Published under the terms of the GNU General Public License Design by Interspire