bashperlubuntu-22.04

bash perl run argument as command


I want to run a passed parameter as a command.

Without using a parameter, it works as I expect:

echo 'Hello world' | perl -0777snE 'print'

Output:

Hello world

Using a parameter instead, no output appears:

options='print'
echo 'Hello world' | perl -0777snE '$o' -- -o="$options"

How can I solve the problem?


Solution

  • options contains Perl code to execute. Simply pass the code to -e.

    perl -0777ne"$options"
    

    If you want to pass the code to Perl by variable for some unseen reason, you will need to ask Perl to execute the string as Perl code. eval EXPR achieves this.

    perl -s0777ne'eval $o; die $@ if $@;' -- -o="$options"
    

    Either way, code is an input. This is a usually a very bad idea. There are security concerns, it's fragile, it requires advanced skills, it's hard to maintain backward compatibility through upgrades, etc.