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?

7
  • 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
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.