12

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

codeforester
  • 39,467
  • 16
  • 112
  • 140
kulan
  • 1,353
  • 3
  • 15
  • 29
  • Do you want to loop through files recursively, or just the files in the given directory, not its children? – kojiro May 01 '14 at 13:35
  • 1
    Just the files in the given directory, not the files from subdirectories – kulan May 01 '14 at 13:36

3 Answers3

25

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"
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • For bash 3, you replace "shopt -s globstar" with "find "$directory""? – kulan May 01 '14 at 13:41
  • @kulan You can use `find` with any version of bash since it's an external command. And `find` is powerful in its own right, but if it's possible to do what you want in pure bash, you can avoid `forking`. – kojiro May 01 '14 at 13:42
  • No, it's just that I'm beginning to learn bash scripting, I was unclear about what you said, so I wanted to make sure. Perhaps I would need it in the future. – kulan May 01 '14 at 13:46
  • @kulan you should definitely learn to [use `find`](http://mywiki.wooledge.org/UsingFind). It's complex, but extremely useful. – kojiro May 01 '14 at 13:48
3

Try

dir="${GOL_HOME}/test_dir"
file="file_*.csv"
for file in `cd ${dir};ls -1 ${file}` ;do
   echo $file
done 
Farid Haq
  • 3,728
  • 1
  • 21
  • 15
  • best solution for me for file in `cd ./dist/libs;ls -1 ${file}` ;do echo $file cd "./dist/libs/$file" pwd cd ../../.. done – evanjmg Jun 17 '22 at 15:04
-6

You can write this script

 #!/bin/bash

clear
echo "enter the directory path: \n"
read directory
for file in $directory/*; do
    echo $file
done
tarun singh
  • 67
  • 1
  • 6