2

I'm trying to echo a combination of text and variables containing wildcards that I need "unpacked", but I encountered the following behavior:

If I say:

FILENAME=somefile*.txt
echo "something:" $FILENAME

I get:

something: somefile003.txt

Which is what I want, but if I say: If I say:

FILENAME=somefile*.txt
echo "something:"$FILENAME

I get:

something:somefile*.txt

So it seems like if there is no space between quotes and the variable it doesn't glob the wildcard. Is there a way to get it to process the * without adding a space?

DopeGhoti
  • 73,792
  • 8
  • 97
  • 133
Maxim
  • 728
  • 3
  • 12
  • 22
  • It does try to parse the wildcard; there are just no files that match the glob `something:somefile*.txt`. – DopeGhoti Jul 24 '17 at 18:09
  • 1
    If you say `FILENAME = somefile*.txt` your shell will try to execute a program called `FILENAME`. If you say `FILENAME=somefile*.txt` your shell will set a variable called `FILENAME`. Please be precise; it's important. – roaima Jul 24 '17 at 18:11
  • @DopeGhoti I see you've edited the question but how do you know which places really contain a space and which don't, given the question is about the effects seen when there is one or not? – roaima Jul 24 '17 at 18:14
  • The 'what I get' part of the question would be factually incorrect if there had been spaces as `FILENAME` would not have been assigned to something which could have globbed. – DopeGhoti Jul 24 '17 at 18:15
  • Perhaps printf would help: `printf "something:%s\n" $FILENAME`. – jimmij Jul 24 '17 at 18:16
  • Related - [Bash substitution with variable defined from a glob pattern](https://unix.stackexchange.com/questions/210280/bash-substitution-with-variable-defined-from-a-glob-pattern) – roaima Jul 24 '17 at 18:21
  • @DopeGhoti Thanks for the edit, that is what I actually meant, I just typed it in incorrectly when writing the question – Maxim Jul 24 '17 at 18:47

2 Answers2

4

You can glob into an array, thus

FILENAMES=(somefile*.txt)

and reference the first element like this

echo "something:${FILENAMES[0]}"

or all of them like this

echo "somethings:${FILENAMES[@]}"

I would strongly recommend that you "double quote" your variables when you use them. This avoids them being expanded into multiple words unexpectedly.

roaima
  • 107,089
  • 14
  • 139
  • 261
1

Try to define your variable like this:

FILENAME=\ somefile*.txt; # that is, with a leading space ... and then
echo "something:"$FILENAME; 

this gets variable interpolated to... something: somefile*.txt

then this gets wildcard expanded to... something: somefile003.txt

these two arguments then get passed to echo which promptly takes them stdout.