Bash shell expansion help

This is what I have in my directory.

$ ls
test1.txt  test2.txt  test3.txt  test4.txt  test5.txt  test_script.sh

This is what my shellscript looks like.

#!/bin/bash

for  filename in /shell_expansion/*.txt; do
           for ((i=0; i<=3; i++)); do
               echo "$filename"
           done
done

This is what happens when I run my shellscript.

./test_script.sh
/shell_expansion/*.txt
/shell_expansion/*.txt
/shell_expansion/*.txt
/shell_expansion/*.txt

I don't understand why shell expansion isn't happening on the . Why am I getting /shell_expansion/.txt instead of /shell_expansion/test1.txt and so on?

The

for  filename in /shell_expansion/*.txt

is looking for files with names ending with .txt in the directory /shell_expansion/ ; not for files ending with that string in the current directory.

If you're looking for files in a subdirectory of your current working directory, maybe you wanted something more like:

for  filename in ./shell_expansion/*.txt

(note the added leading period) or just remove the leading slash from the pathname:

for  filename in shell_expansion/*.txt

An alternate approach could be with: ./test_script.sh

#!/bin/bash
list_dir="." 
# list_dir is set to current pwd, 
# as you have shown your *txt files reside in the same pwd as your script...
# this actualy means, the 'cd $list_dir;' part would not be required, 
# but this would let you get the plain file names, rather than with the full path.
for filename in $(cd "$list_dir";ls *.txt | head -n4 )
do      echo "$filename"
done

Have fun

/shell_expansion/ is my current directory.

I tried it both ways with no luck. It still won't expand the *.

$ ./test_script.sh
./shell_expansion/*.txt
./shell_expansion/*.txt
./shell_expansion/*.txt
./shell_expansion/*.txt


]$ ./test_script.sh
shell_expansion/*.txt
shell_expansion/*.txt
shell_expansion/*.txt
shell_expansion/*.txt

Are those files in the directory /shell_expansion or ./shell_expansion ? In what directory are the files located?

Not that we don't believe you, but what you're saying doesn't make sense...

Please show us the output from the commands:

pwd
ls -l /shell_expansion/*.txt $HOME/shell_expansion/*.txt ./shell_expansion/*.txt ./*.txt

(both on standard output and on standard error output).

And, just for the fun of it, please explain why you want to print the names of all of the names of files ending in the string .txt in a directory four times.