0

I try to loop through two directories and echo all files with a given extension with this script:

#!/bin/bash
FOLDERS=/sdd/DATA/ /sdc/storage/
for d in $FOLDERS; do
echo "$d"
  FILES=$d*.txt
  for f in $FILES; do
    echo "$f"
  done
done

but I do not get this script to work! I get bash: sdc/storage/ is a directory

3
  • 1
    I would expect you to get an error like -bash: /sdc/storage: is a directory Commented Aug 27, 2019 at 21:59
  • 2
    ...which can be fixed by enclosing /sdd/DATA/ /sdc/storage/ in quotation marks. (Without, that line sets FOLDERS=/sdd/DATA/ and then attempts to execute /sdc/storage/, which doesn't work because -- guess what -- it's a directory. ;-) ) Even better would be to be aware of filenames with spaces in them, and either doing "the IFS thing" with for ... in ..., or using find ... -exec .... Commented Aug 27, 2019 at 22:01
  • 1
    @DevSolar, ...*could* be fixed that way, but it'd be very bad practice to define FOLDERS as a string rather than an array. Aiming for the most obvious issue first, it'd break the moment you had a directory name with spaces. Commented Aug 27, 2019 at 22:11

1 Answer 1

4

Doing this right would look like:

#!/bin/bash
folders=( /sdd/DATA/ /sdc/storage/ )
for d in "${folders[@]}"; do
  echo "$d"
  files=( "$d"*.txt )
  printf '%s\n' "${files[@]}" # print the files array, one per line
done

Note:

  • array=( "first item" "second item" ) defines a two-item array; "${array[@]}" expands to those items.
  • When expanding an element, we want to quote the parts the shell shouldn't string-split or glob-expand, but leave any glob patterns unquoted; thus, "$d"*.txt.
  • We're using lowercase names for user-defined variables. This is per POSIX-defined recommendation, which specify all-caps names as used for variables meaningful to the operating system and shell, whereas all other names are reserved for application use.
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.