0
cat /tmp/testme
#!/usr/bin/env  python3
import sys
print(sys.argv[0])
print(sys.argv[1])

It is simple ,just to print argument passed from bash to python.

x="i am a book"
/tmp/testme "i am a book"
/tmp/testme
i am a book

The string i am a book can passed into python program as a whole string.

/tmp/testme  ${x}
/tmp/testme
i
echo ${x}
i am a book

Why python can't deal with ${x} i am a book as a whole,it get only the first character in the string as argument.

3
  • Your question is very unclear. Could you please elaborate a little and tell us your goal and what the code is supposed to do? Commented Jun 1, 2019 at 1:25
  • 2
    Put the argument in quotes: /tmp/testme "${x}" Commented Jun 1, 2019 at 1:26
  • 1
    Without double-quotes around it, the shell will try to split the variable's value into words and also expand anything that looks like a wildcard into a list of matching filenames. You generally don't want either of these (and if you do, you probably want it in a different form), so you should almost always put double-quotes around variable references. Commented Jun 1, 2019 at 1:49

1 Answer 1

1

When you execute the line /tmp/testme ${x}, bash will expand the contents of x, and will ultimately execute /tmp/testme i am a book. Therefore, sys.argv will become ['/tmp/testme', 'i', 'am', 'a', 'book'].

To achieve the desired behaviour, ${x} should be quoted, like "${x}". Then bash will execute /tmp/testme 'i am a book'.

Here is an example with a bash script. With set -x, bash will print commands and their arguments as they are executed, after all variables have been evaluated.

$ cat testme
#!/usr/bin/env python3
import sys
print(sys.argv)

$ cat exampleBashScript.sh 
#!/usr/bin/env bash
set -x

x="i am a book"
./testme ${x}
./testme "${x}"

$ ./exampleBashScript.sh 
+ x='i am a book'
+ ./testme i am a book
['./testme', 'i', 'am', 'a', 'book']
+ ./testme 'i am a book'
['./testme', 'i am a book']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.