0

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.

ceving
  • 3,579
  • 5
  • 24
  • 30
tpsaitwal
  • 151

1 Answers1

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"
villapx
  • 682
  • 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 05:36