3

I'm trying to iterate over each file in a directory. Here's my code so far.

while read inputline
do
  input="$inputline"
  echo "you entered $input";

if [ -d "${input}" ]
  then
    echo "Good Job, it's a directory!"

    for d in $input
      do
        echo "This is $d in directory."
      done
   exit

my output is always just one line

this is $input directory.

why isn't this code working? what am I doing wrong?

Cool. When I echo it prints out

$input/file

Why does it do that? Shouldn't it just print out the file without the directory prefix?

Mawnster
  • 633
  • 3
  • 11
  • 18

2 Answers2

7
for d in "$input"/*
pixelbeat
  • 29,113
  • 9
  • 48
  • 60
  • why add double quote " around $input, is there a good reason doing this? I found out " for d in $input/* " also works. Thanks. – Lion Lai Mar 23 '17 at 04:00
  • 1
    If $input has spaces etc. you need to quote. – pixelbeat Mar 23 '17 at 22:24
  • 1
    @LionLai See also [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Dec 20 '21 at 07:42
3

If you want to simplify it somewhat and get rid of the directory check, you could just write it to work on files and directories, perhaps something like:

read inputline
ls "$inputline" | while read f; do
    echo Found "$f"
done
DigitalRoss
  • 139,415
  • 24
  • 238
  • 326