I'm writing a reusable function, so I need the argument to be as flexible as possible.
Consider a simple example:
function testf(){
print ./*.$1
}
This works. For example, with testf mp3
it lists all the files ending with .mp3
in an array, making possible the use of for
loops. But this way it only allows me to work with the extension name.
Therefore, I tried:
function testf(){
print ./$1
}
However, it doesn't work. Using testf *.mp3
, unlike using print *.mp3
in the terminal, it will only pass the first matching string instead of the whole array.
Any suggestion?
ists all the files ending with .mp3 in an array ... there is no array involved in your question.
But to your problem: First, you want to pass to your function a wildcard pattern, but this is not what you are actually doing. testf *.mp3
expands the pattern before the function is invoked (this process is called filename generation), and your testf
gets just a list of files as parameters. You can pass a pattern, but you have to ask the shell not to expand it:
testf '*.mp3'
In this case, your $1
indeed will contain the string *.mp3
. However, your print ./$1
will still not work. The reason is that filename generation occurs before parameter expansion (which is the process where $1
is replaced by the string it contains). Again, you have to ask the shell to do it the other way round:
print ./${~1}