Search code examples
pythonbashshzshexec

How to understand the "$0" "$@" after `exec python3 "$0" "$@" `


I do not quite follow the following code snippet from https://github.com/nodejs/node/blob/main/configure#L6-L16.

In particular, what does "$0" "$@" mean right after sh -c ```<command>``` ?

For now, I understand that by running ./<this_file_name>, the program would check the existing available python and execute the same file (as exec will exit the current program after it successfully finished ) once we find the existing version.


#!/bin/sh

# Locate an acceptable Python interpreter and then re-execute the script.
# Note that the mix of single and double quotes is intentional,
# as is the fact that the ] goes on a new line.
_=[ 'exec' '/bin/sh' '-c' '''
command -v python3.11 >/dev/null && exec python3.11 "$0" "$@"
command -v python3.10 >/dev/null && exec python3.10 "$0" "$@"
exec python "$0" "$@"
''' "$0" "$@"
]
del _
import sys
...

Solution

  • From man sh

    -c  Read commands from the command_string operand instead of
        from the standard input.  Special parameter 0 will be set
        from the command_name operand and the positional parameters
        ($1, $2, etc.)  set from the remaining argument operands.
    

    an example :

    /bin/sh -c '
       echo \$0 is $0
       echo "All the arguments are : $@"
    ' dollar-0 arg1 arg2 arg3 ...
    

    Output is :

    $0 is dollar-0
    All the arguments are : arg1 arg2 arg3 ...