0

I do not know if this topic was reached or not bot couldn't find anything related.

I have a bash script and I want to do a for loop through multiple directories with the mention that I want to output in a log file only *.txt/files but the loop to don't go on sub-directories.

My desire is to use the directories in variables. I am using an array where I wrote the directories I search for them. When the script is ran the output is what is in array, not what is in the directories...

This is how my code look now, what should I do?:

#!/bin/bash

l=/home/Files/Test1/
j=/home/Files/Test2/
k=/home/Files/Test3/

arr=("$l" "$j" "$k")

for i in "${arr[*]}"
do
  echo "$i"  >> test
done

Thank you for any help!

2
  • 2
    I want to do a for loop through multiple directories You say that, yet I think you meant that you want to loop through files in multiple directories, not through directories. Commented Aug 7, 2020 at 11:17
  • yes, sorry for confusion.. Commented Aug 7, 2020 at 11:39

1 Answer 1

2

Just find the actual files.

find "${arr[@]}" -maxdepth 1 -type f >> test

You could depend on shell filename expansion:

for dir in "${arr[@]}" # properly handle spaces in array values
do
      for file in "$dir"/*; do
          # check for empty dir
          if [ -f "$file" ]; then
              # Use printf, in case file is named ex. `-e`
              printf "%s\n" "$file"
          fi
      done
# don't reopen the file on each loop, just open it once
done >> test

but that's a lot more, just find it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.