2

Consider this simple script:

#!/bin/bash
DIR="$1"

for f in "$DIR"; do
    if [[ "$f" == "*.txt" ]];
    then
        echo "Filename is $f"
fi
done

I want to only return files with .txt extension. Calling the script with:

./script1 /home/admin/Documents

Returns nothing. No error, just blank. What is wrong?

LightningWar
  • 915
  • 1
  • 19
  • 35

1 Answers1

10

I assume that you expect to loop through all files within the directory you pass. To do that, you need to change your loop:

for file in "$1"/*

It's worth mentioning that for doesn't have any built-in behaviour to enumerate items in a directory, it simply iterates over the list of words that you pass it. The *, expanded by the shell, is what results in the loop iterating over a list of files.

Your condition would need modifying too, as the * needs to be outside of quotes (and the rest doesn't need to be inside them, either):

if [[ $f = *.txt ]]

But you can avoid the need for the conditional by directly looping through all files ending in .txt:

for file in "$1"/*.txt

You may also want to consider the case where there are no matches, in which case I guess you expect the loop not to run. One way to do that in bash would be:

# failing glob expands to nothing, rather than itself
shopt -s nullglob 

for file in "$1"/*.txt
    # ...
done

# unset this behaviour if you don't want it in the rest of the script
shopt -u nullglob
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141