2

I was trying to write a python script like this:

import sys

print sys.argv[1]
print sys.argv[2]

Let's call it arg.py, and run it in command line:

python arg.py one two

it printed: one two.

Everything was fine.

Then I wanted it to be handy so I put arg.py in my $PATH and gave it permission to exacuate so wherever I'm I can simply type arg in command line to run this script. I tried

arg one two

but it failed. The exception said:"bash: test: one: unary operator expected". But if I just do

arg one

it worked fine.

My question is: why I can't pass multiple arguments like this? And what is the right way?

Thanks!

1
  • How have you added the script to your path? Commented Feb 13, 2014 at 18:18

2 Answers 2

4

You probably named your script test, which is a Bash builtin name. Name it something else.

$ help test
test: test [expr]
    Evaluate conditional expression.

    Exits with a status of 0 (true) or 1 (false) depending on
    the evaluation of EXPR.  Expressions may be unary or binary.  Unary
    expressions are often used to examine the status of a file.  There
    are string operators and numeric comparison operators as well.

    The behavior of test depends on the number of arguments.  Read the
    bash manual page for the complete specification.

    ...

That's why you're getting the error from bash:

bash: test: one: unary operator expected
                   ^--------- because it expects an operator to go before 'two'
             ^-------- and test doesn't like the argument 'one' you've provided
       ^-------- because it's interpreting your command as the builtin 'test'
  ^--- Bash is giving you an error
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing answer, thanks! I didn't know "test" was a bash builtin.
0

You should parse command line arguments in Python using argparse or the older optparse.

Your script, as it is, should work. Remember to put a shebang line that tells bash to use Python as interpreter, e.g. #! /usr/bin/env python

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.