0

I would like to iterate a loop over all the file present in a directory using shell script. Further, I would like to display the contents from each file. I am passing directory as a command line argument.

I have a simple loop as follows:

for file in $1
do
    cat $file
done

If I run

sh script.sh test

where test is a directory, I get content of first file only.

Could anyone please help me in this?

Sujit Devkar
  • 1,195
  • 3
  • 12
  • 22

2 Answers2

1

Try something like:

 for file in $1/*
 do
     if [[ -f $file ]] ##you could add -r to check if you have read permission for file or not
     then
         cat $file
     fi
 done
SMA
  • 36,381
  • 8
  • 49
  • 73
1

couple of alternatives:

compact modification of SMA's code:

for file in $1/*
 do
      [[ -f $file ]] && cat $file
 done

or use find:

find $1 -type f -exec cat \{\} \;
Droopy4096
  • 311
  • 1
  • 10
  • but, I need only file name. Here, I get file name of the parent directory also. e.g. if my files are in test directory then the file name I get is "test/file.txt". How to get only "file.txt" – Sujit Devkar Mar 21 '15 at 10:16
  • Actually I was looking for name=$(basename "$file"), but thanks. – Sujit Devkar Mar 21 '15 at 10:42