-2

This question already has an answer here:

I have a assignment in which I am passing a file pattern to a function as below:

line=FILE*.txt
getFlag $line

While the function is as below:

function getFlag
{
    filepattern=$1
    echo "File pattern is: $filepattern"
}

I need the output as

File pattern is: FILE*.txt

While I am getting output as a matching file name present in the folder as below:

File pattern is: FILE123.txt

Though I am passing a file pattern as a variable to the function it does not prevent variable expansion and the file name matching with the pattern in variable is getting passed.

Any help upon above much appreciated.

marked as duplicate by Gilles bash Oct 21 '16 at 22:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

As ilkkachu said, you could single- or double-quote the argument that you're passing to this function:

line='FILE*.txt'

or

line="FILE*.txt"

Those tell Bash to perform no substitution or some substitution without doing filename expansion, respectively.

Another option would be to escape the * when setting line, then pass the argument to the function using quotes:

line=FILE\*.txt
getFlag "$line"
  • 1
    It's the getFlag $line command that expands (and globs) the variable and needs the quotes. The assignment itself doesn't actually expand, but it's not a bad habit to use quotes there too, since almost all other contexts will expand (and glob) the variable. compare foo=*; echo "$foo" with foo="*"; echo $foo. – ilkkachu Oct 21 '16 at 15:23
  • @ilkkachu even if I am doing getFlag "$line" or getFlag '$line', it still expands – tpsaitwal Oct 24 '16 at 5:36

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