How to embed and run a multi-line perl script stored in a bash variable in a bash script (without immediately running perl) [duplicate]

℡╲_俬逩灬. 提交于 2020-02-29 07:05:28

问题


How do I replace [RUN_ABOVE_PERL_SORTING_SCRIPT_HERE] with something that runs this perl script stored in a bash variable?

#!/usr/bin/env bash

# The perl script to sort getfacl output:
# https://github.com/philips/acl/blob/master/test/sort-getfacl-output

find /etc -name .git -prune -o -print | xargs getfacl -peL | [RUN_ABOVE_PERL_SORTING_SCRIPT_HERE] > /etc/.facl.nogit.txt

Notes:

  1. I do not want to employ 2 files (a bash script and a perl script) to solve this problem; I want the functionality to be stored all in one bash script file.
  2. I do not want to immediately run the perl script when storing the perl-script variable, because I want to run it later in the getfacl(1) bash pipeline shown below.
  3. There's many similar stackoverflow questions+answers, but none that I can find (that has clean-reading code, anyway?) that solve both the a) multi-line and b) delayed-execution (or the embedded perl script) portion of this problem.
  4. And to clarify: this problem is not specifically about getfacl(1), which is simply an catalyst to explore how to embed perl scripts--and possibly other scripting languages like python--into bash variables for delayed execution in a bash script.)

回答1:


Employ the bash read command, which reads the perl script into a variable that's executed later in the bash script.

#!/usr/bin/env bash

# sort getfacl output: the following code is copied from:
# https://github.com/philips/acl/blob/master/test/sort-getfacl-output

read -r -d '' SCRIPT <<'EOS'
#!/usr/bin/env perl -w

undef $/;
print join("\n\n", sort split(/\n\n/, <>)), "\n\n";
EOS

find /etc -name .git -prune -o -print | xargs getfacl -peL | perl -e "$SCRIPT" > /etc/.facl.nogit.txt



回答2:


This is covered by Run Perl Script From Unix Shell Script.

As they apply here:

  1. You can pass the code to Perl using -e/-E.

    perl -e"$script"
    

    or

    perl -e"$( curl "$url" )"
    
  2. You can pass the code via STDIN.

    printf %s "$script" | perl -e"$script"
    

    or

    curl "$url" | perl
    

    (This won't work for you because you need STDIN.)

  3. You can create a virtual file.

    perl <( printf %s "$script" )
    

    or

    perl <( curl "$url" )
    
  4. You can take advantage of perl's -x option.

    (Not applicable if you want to download the script dynamically.)


All of the above assume the following command has already been executed:

url='https://github.com/philips/acl/blob/master/test/sort-getfacl-output'

Some of the above assume the following command has already been executed:

script="$( curl "$url" )


来源:https://stackoverflow.com/questions/60139380/how-to-embed-and-run-a-multi-line-perl-script-stored-in-a-bash-variable-in-a-bas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!