What does exec ${PERL-perl} -Sx $0 ${1+“$@”} mean

2019-08-19 08:17发布

问题:

I'm given a task to convert a shell script which contains Shell script, Perl code to Python.

I managed to convert the Perl code to Python.

But there is this shell script statement which I didn't understand.

#! /usr/bin/sh
exec ${PERL-perl} -Sx $0 ${1+"$@"}
#! /opt/tools/perl5/bin/perl
Some Perl code which I converted to Python

What does this 2nd line means?

I understood that $0 will be evaluated to the script name.

And I'm assuming that ${PERL-perl} will evaluate to whatever Perl interpreter is installed on the machine (correct me if I'm wrong and also please let me know how do I mention the similar thing for Python).

Can someone explain what those remaining parameters in that exec command do?

回答1:

${PERL-perl} is a parameter expansion: if the PERL shell variable is unset, use perl, else use the content of PERL. (Arguably, this should be ${PERL:-perl}, because if PERL is set but empty, the empty string will be used.)

${1+"$@"} stands for "if $1 is set, use "$@" (all positional parameters), else substitute null". This is a hack for older shells that get confused by "$@" if there are no positional parameters and expand to a single parameter instead of none at all. Bash would work with just "$@" instead.

For the options to perl, see perldoc perlrun.