linux iterate over files in directory

2019-05-23 16:35发布

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?

2条回答
家丑人穷心不美
2楼-- · 2019-05-23 17:14
for d in "$input"/*
查看更多
聊天终结者
3楼-- · 2019-05-23 17:36

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
查看更多
登录 后发表回答