12

Obviously this shell script is calling itself as a Python script:

#!/bin/sh
## repo default configuration
##
REPO_URL='git://android.git.kernel.org/tools/repo.git'
REPO_REV='stable'
magic='--calling-python-from-/bin/sh--'
"""exec" python -E "0ドル" "$@" """#$magic"
if __name__ == '__main__':
 import sys
 if sys.argv[-1] == '#%s' % magic:
 del sys.argv[-1]
del magic
:
:

(Whole script: https://android.googlesource.com/tools/repo/+/v1.0/repo)

Can anyone explain

  • the purpose of calling it this way?
    Why not having #!/usr/bin/env python in the first line so it gets interpreted as Python script from the beginning?

  • the purpose of adding that magic last command line argument, that is removed afterwards in the beginning of the Python code?

Vadim Kotov
8,2848 gold badges51 silver badges63 bronze badges
asked Apr 6, 2011 at 11:08
3
  • 1
    Smells like bureaucracy to me. Commented Apr 6, 2011 at 11:14
  • @Will: Do you mean the author had some non-technical constraint that allows only shell scripts, no Python scripts; so he wrote a Python script that is formally a shell script? Commented Apr 8, 2011 at 12:53
  • I guess I have to work on my dry sense of humour. Ingo's answer is the most likely real reason. Commented Apr 8, 2011 at 13:13

1 Answer 1

8

Your first question: this is done to fix unix systems (or emulations thereof) that do not handle the #! correctly or at all. The high art is to make a script that is correct in shell as well as in the other language. For perl, one often sees something like:

exec "/usr/bin/perl"
 if 0;

The exec is interpreted and executed by the shell, but the perl interpreter sees a conditional statement (.... if ...) and does nothing because the condition is false.

Vadim Kotov
8,2848 gold badges51 silver badges63 bronze badges
answered Apr 6, 2011 at 11:30
Sign up to request clarification or add additional context in comments.

2 Comments

Could also be used on systems which do handle #! correctly but are explicitly using sh to interpret scripts in a particular directory.
Or even to handle systems which don't definitely have /usr/bin/env.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.