can we source a shell script in perl script

前端 未结 7 754
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 04:54

can we source a shell script in the perl script??

Example: Program 1:

cat test1.sh
#!/bin/ksh
DATE=/bin/date

program 2:

<         


        
7条回答
  •  时光说笑
    2021-01-15 05:17

    I met a close need from the OP's in a project, where I needed to configure a Perl script (it could be any language, for that matter) by sourcing a shell script defining the environment.

    I personally rarely use sourcing for anything else than configuration and environment setting (the only other good reason for sourcing I am aware of, is for importing functions in shell scripts, but I may be missing some creative usage).

    My solution was to source the configuration script from a launcher script (in shell), and then to exec the Perl script in the same launcher script (replacing effectively the launcher script by the Perl script, thus avoiding to create a subprocess).

    # configuration_script.sh
    export MY_ENV_VAR1=value1
    export MY_ENV_VAR2=value2
    
    # launcher_script.sh
    . configuration_script.sh # source the configuration
    exec /path/to/main_script.pl "$@" # could be any other language here (Python, Tcl, Ruby, C, Java...)
    

    The "$@" allows to pass the command line arguments from the launcher script to the main script.

    It's then up to the main script author to retrieve the environment (e.g. with $ENV{MY_ENV_VAR1} in Perl).

提交回复
热议问题