osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

uses both shell and python codes in one script.


On 03Oct2019 23:55, Chris Angelico <rosuav at gmail.com> wrote:
>On Thu, Oct 3, 2019 at 11:41 PM Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
>> I'm very confusing on the following part in this script:
>>
>> ----
>> ''':' # begin python string; this line is interpreted by the shell as `:`
>> which python  >/dev/null 2>&1 && exec python  "$0" "$@"
>> which python3 >/dev/null 2>&1 && exec python3 "$0" "$@"
>> which python2 >/dev/null 2>&1 && exec python2 "$0" "$@"
>> >&2 echo "error: cannot find python"
>> exit 1
>> '''
>> ----
>>
>> Any hints for the meaning of several ' used above?
>
>The hint is there in that line, and stems from the way two different
>parsers (Python and sh) interpret the line. [...]
>
>In the shell, the first two are an
>empty string, then ':' is a colon, which introduces a label (the fact
>that it's in quotes is irrelevant to the shell). So there's an empty
>label followed by a shell comment.

No. ":" is a synonym for "true". (Like "[" is a synonym for "test".)

There aren't labels in the shell. This is just a dummy "true" command, 
with a comment.

Since I'm here, I'll seize the opportunity to endorse Chris' earlier 
statement: just use "#!/usr/bin/env python3" as the opening shebang line 
and don't worry about embedding complex shell to "locate" python.  
Instead, expect the caller's environment to be correctly set up, and 
therefore for the "python3" command to find the preferred python 
interpreter.

Cheers,
Cameron Simpson <cs at cskk.id.au>