-1

I want to write a very basic script that return the file names of *txt files in the current directory. I wrote the following code:

#!/bin/bash
FILES=$(ls *txt)

for FILE in $FILES
do
echo "$File"
done

The output of the script are 5 empty lines instead of the names of the 5 *txt files in the directoy.

  • 1
    I believe it should be `echo "$FILE"`, not `echo "$File"`. That would explain the 5 empty lines. Also see [List all files in a directory with a certain extension](https://stackoverflow.com/q/18823609/608639), [Loop through all the files with a specific extension](https://stackoverflow.com/q/14505047/608639), [How do I perform an action on all files with a specific extension in subfolders?](https://unix.stackexchange.com/q/50313/56041), [Recursively find files with a specific extension](https://stackoverflow.com/q/25693638/608639), etc. – jww Jul 08 '17 at 12:45
  • 2
    `File` is never set in your code, but apart from that your loop is severely broken anyway. See http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29. – melpomene Jul 08 '17 at 12:47
  • Possible duplicate of [Loop through all the files with a specific extension](https://stackoverflow.com/questions/14505047/loop-through-all-the-files-with-a-specific-extension) – jww Jul 08 '17 at 13:14

1 Answers1

1

There are several things wrong with this script:

  1. FILES is not an array.
  2. Never use the output of ls programmatically.
  3. FILE and File are two different variables; names are case-sensitive.
  4. All-uppercase names are reserved for use by the shell.

Your code should be

files=( *txt )  # ( *.txt ) would probably be cleaner
for file in "${files[@]}"; do
  echo "$file"
done

Be aware, though, that depending on your shell settings, the assignment to files can have three different outcomes if there are no matching files:

  1. files could contain a single element, literally *txt (the default)
  2. files could be empty (with nullglob set)
  3. The pattern match could produce an error (with failglob set)
chepner
  • 497,756
  • 71
  • 530
  • 681