I'm having difficulties passing arguments to a embedded bash script.
#!/bin/bash/
function my_function() {
MYPARSER="1ドル" python - <<END
<<Some Python Code>>
class MyParser(OptionParser):
def format_epilog(self, formatter):
return self.epilog
parser=MyParser(version=VER, usage=USAGE, epilog=DESC)
parser.add_option("-s", "--Startdir", dest="StartDir",
metavar="StartDir"
)
parser.add_option("-r", "--report", dest="ReportDir",
metavar="ReportDir"
)
<<More Python Code>>
END
}
foo="-s /mnt/folder -r /storagefolder/"
my_function "$foo"
I've read Steve's Blog: Embedding python in bash scripts which helped but I'm still unable to pass the argument. I've tried both parser and myparser as environmental variables.
Is it as simple as defining 2ドル and passing them individually?
Thanks
1 Answer 1
You're overcomplicating this rather a lot. Why mess with a parser where
value="hello" python -c 'import os; print os.environ["value"]'
Or, for a longer script:
value="hello" python <<'EOF'
import os
print os.environ["value"]
EOF
If you need to set sys.argv for compatibility with existing code:
python - first second <<<'import sys; print sys.argv'
Thus:
args=( -s /mnt/folder -r /storagefolder/ )
python - "${args[@]}" <<'EOF'
import sys
print sys.argv # this is what an OptionParser will be looking at by default.
EOF
answered Jun 25, 2015 at 21:33
Charles Duffy
300k43 gold badges442 silver badges498 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
David Maddox
How would you pass multiple values?
Charles Duffy
The same way you pass a single value.
a=b c=d python ... puts both a and c in os.environ. And the args example already passes multiple values.default
functionkeyword in bash is bad form: It's incompatible with POSIX sh, but -- unlike most of bash's incompatibilities -- gives you absolutely no improvement in expressiveness or functionality over the POSIX-standard syntax. Just usemyfunc() {, notfunction myfunc() {.