I have a weird issue with bash / optparse. I need to pass string to my python script when string is defined.
I use following code:
./lol.py `if [ -n "$URL" ]; then echo -u \"$URL\"; fi`
and here is python script:
def main():
parser = OptionParser()
parser.add_option("-u", dest="url")
opts, args = parser.parse_args()
print opts.url
When I test my bash expression it appears to be working:
user@fomce02:~$ URL="http://lol.com/my project/"
user@fomce02:~$ echo `if [ -n "$URL" ]; then echo -u \"$URL\"; fi`
-u "http://lol.com/my project/"
However when I run python script with an argument
user@fomce02:~$ ./lol.py `if [ -n "$URL" ]; then echo -u "$URL"; fi`
http://lol.com/my
it truncates part of string after whitespace.
Could you explain why it is happening and how to get it work?
This is because the quotes you are sending to the script are literal, not syntactic. That means lol.py
receives the parameters "http://lol.com/my
and project/"
. If you want to pass the result of a command as a single parameter you have to use syntactic quotes around the code:
./lol.py "$(if [ -n "$URL" ]; then echo -u "$URL"; fi)"
Also fixed the backticks - If you're using Bash it's highly recommended to use $()
. Note that the quoting context is different inside and outside the command substitution, so there's no danger of the outer quotes affecting the inner quotes.