Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Shell list files using "for" loop

Tags:

bash

for-loop

I use the following Bash Shell script to list the ".txt" files recursively under the current directory :

#!/bin/bash
for file in $( find . -type f -name "*.txt" )
do
  echo $file
  # Do something else.
done

However, some of the ".txt" files under the current directory have spaces in their names, e.g. "my testing.txt". The listing becomes corrupted, e.g. "my testing.txt" is listed as

my
testing.txt

It seems that the "for" loop uses "white space" (space, \n etc) to separate the file list but in my case I want to use only "\n" to separate the file list.

Is there any way I could modify this script to achieve this purpose. Any idea.

Thanks in advance.

like image 303
user1129812 Avatar asked Feb 04 '12 07:02

user1129812


People also ask

How do I list files in a bash script?

To see a list of all subdirectories and files within your current working directory, use the command ls .

How do I loop all 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 do I loop all files in a directory?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.


1 Answers

If you're using bash 4, just use a glob:

#!/bin/bash                                                                     

shopt -s globstar

for file in **/*.txt
do
  if [[ ! -f "$file" ]]
  then
      continue
  fi
  echo "$file"
  # Do something else.                                                          
done

Be sure to quote "$file" or you'll have the same problem elsewhere. ** will recursively match files and directories if you have enabled globstar.

like image 70
FatalError Avatar answered Sep 22 '22 12:09

FatalError