Ubuntu – Expansion with *.txt in the shell doesn’t work if no .txt file exists

bashcommand line

I was playing around with expansion, and I noticed a peculiar behavior. I tried doing:

echo ./*.txt

And I didn't have any .txt file in my current directory. The output I got was:

./*.txt

I'm just curious: Why did I get this? I was expecting to not get any output.

PS: When I did have a .txt file, the expansion was correctly interpreted. In other words, say I had a file, smthn.txt, the echo actually echoed current_directory/smthn.txt.

Best Answer

Adapting from the bash shell man page,

bash scans each word for the characters *, ?, and [. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern. If no matching filenames are found, and the shell option nullglob is not enabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed.

In this case I presume nullglob is not enabled, so the word is left unchanged - hence the output you see.