0

I'm trying to refresh my bash scripting skills. I got stuck on the dumbest thing:

for f in "$(ls)"; do
    [[ $f == *.txt ]] && printf "%s\n" "$f"
done

What is wrong with this loop? I'm simply trying to print all the .txt files in the current dir. It seems that pattern match is wrong..

alfredopacino
  • 183
  • 1
  • 7
  • 5
    First read [Why *not* parse `ls` (and what to do instead)?](https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead). Then you don't need a loop for that, `ls *.txt` will do. Also [this](https://www.gnu.org/software/libc/manual/html_node/Globbing.html). – schrodingerscatcuriosity Mar 28 '21 at 00:28
  • 2
    Also, in this case, using `set -x` to see the command being executed after expansions will likely be revealing. – fra-san Mar 28 '21 at 00:59
  • @schrodigerscatcuriosity I'll read that, but this just a toy script I've made and I'm curious about why it doesn't work. – alfredopacino Mar 28 '21 at 18:21
  • @fra-san In this case the debug mode doesn't help I think, it just prints out the whole list I'm iterating over, and the list contains both .txt and not .txt files – alfredopacino Mar 28 '21 at 18:23
  • @alfredopacino that's waht fra-san was pointing out. The double-quotes in the command substitution causes the list of files to be printed as one line, remove the dqs. – schrodingerscatcuriosity Mar 28 '21 at 18:57
  • 1
    ...and it will make clear that 1) the loop body is executed just once, no matter how many files are listed by `ls`; 2) the whole list of files matches the pattern `*.txt` if the _last_ file name ends in `.txt`, no matter what the other file names are. – fra-san Mar 28 '21 at 20:30

0 Answers0