Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through all files in a directory [duplicate]

Tags:

bash

shell

loops

I want to write a shell script that will loop through all the files in a directory and echo "put ${filename}". Can anyone point me in the right direction?

like image 787
skline Avatar asked Dec 14 '11 22:12

skline


People also ask

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How run multiple files in Linux?

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint). Then, type the following three commands on one line, separated by semicolons, and press Enter.


1 Answers

For files and directories, not recursive

for filename in *; do echo "put ${filename}"; done 

For files only (excludes folders), not recursive

for file in *; do      if [ -f "$file" ]; then          echo "$file"      fi  done 

For a recursive solution, see Bennet Yee's answer.

like image 73
Oliver Charlesworth Avatar answered Oct 12 '22 19:10

Oliver Charlesworth