Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through files in a given directory [duplicate]

Tags:

bash

I am trying to loop through every file in a user specified directory. Here's my code:

clear
echo "enter the directory path: \n"
read directory
for file in $directory; do
    echo $file
done

My input, e.g.: /home/user/Downloads

Output I get: /home/user/Downloads

If I use

clear
for file in *; do
    echo $file
done

It works, but it shows only the contenets of current directory

like image 573
kulan Avatar asked May 01 '14 13:05

kulan


2 Answers

If you only want the files non-recursively in the current directory, combine what you have:

read -p 'Enter the directory path: ' directory
for file in "$directory"/*; do
  echo "$file"
done

If you want to loop recursively and you have bash 4, it's not much harder:

shopt -s globstar
for file in "$directory"/**/*; do …

But if you only have bash 3, you'd be better off using find.

find "$directory"
like image 127
kojiro Avatar answered Oct 13 '22 01:10

kojiro


Try

dir="${GOL_HOME}/test_dir"
file="file_*.csv"
for file in `cd ${dir};ls -1 ${file}` ;do
   echo $file
done 
like image 21
Farid Haq Avatar answered Oct 13 '22 01:10

Farid Haq