0

I have the following shell script in bash:

function zzqfoo {
    python ~/my/dir/path/zzqfoo.py $(abspath $1) $2
}

The idea is to call the python program "zzqfoo.py" with a local filename on the command line, but zzqfoo.py receives the absolute path to the file thanks to $(abspath $1).

However when I call

>>> zzqfoo myfile *

the shell corrupts the * and sends god knows what to zzqfoo.py as second argument.

How do prevent the * from being corrupted? (I want zzqfoo.py to receive the second command line argument as-is.)

Thanks!

  • What does "as-is" mean to you here? What does zzqfoo.py expect in its arguments? – Michael Homer Apr 2 '18 at 5:30
  • I meant that zzqfoo receives the character '*'.... (for which the solutions below work) – Labrador Apr 2 '18 at 6:15
2

the shell corrupts the * and sends god knows what to zzqfoo.py as second argument.

It doesn't "corrupt" the *. It does what it always does: expands the * as wildcard, matching the names of files and directories in the current directory.

You should:

  • quote the * when passing it as an argument
  • quote $1, $2 etc. when using it in the function, so that the shell doesn't do word splitting or wildcard expansion on them

So:

function zzqfoo {
    python ~/my/dir/path/zzqfoo.py "$(abspath "$1")" "$2"
}

And run it so:

zzqfoo myfile '*'
  • You are correct that quoting $1, $2 etc. will prevent word splitting (and it's a good practice anyways!) but it's not necessary for wildcard expansion, since the shell won't perform it on the expanded contents of the variables, so technically it's not needed to solve this problem, only quoting the literal asterisk with '*' is enough to fix this in this particular case. – filbranden Apr 2 '18 at 5:34
  • @FilipeBrandenburger you sure? Try sh -c 'echo $1' _ '*' and check. – Olorin Apr 2 '18 at 5:40
  • Ah sorry my bad, indeed it will perform wildcard expansion if not quoted. (I was probably thinking of variable assignments.) – filbranden Apr 2 '18 at 5:50
1

Quote it:

$ zzqfoo myfile "*"

Or

$ zzqfoo myfile \*

Or

$ zzqfoo myfile '*'

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.