Home > Net >  How can I really call a shell command in my Perl script?
How can I really call a shell command in my Perl script?

Time:08-13

How to execute shell commands, retaining all ENV variables, specifying shell type/instance etc. Having access to all aliases, and setting further aliases.

Example:

#!/usr/bin/perl
system("alias test-alias echo TEST;");
system("test-alias;");
system("echo \$SHELL");

Results in:

sh: line 0: alias: test-alias: not found
sh: line 0: alias: echo: not found
sh: line 0: alias: TEST: not found
sh: test-alias: command not found
/tool/pandora/bin/tcsh

CodePudding user response:

Perl has the special global %ENV that stores all the Environment variables that Perl itself launched with. To get the SHELL environment variable you can just write.

my $shell = $ENV{SHELL};

To get all environment variable.

while ( my ($key,$value) = each %ENV ) {
    printf "%s => %s\n", $key, $value;
}

You also can use this hash to store new environment variables.

$ENV{FOO} = "bla";
system('echo $FOO');

The above will print bla. And sure if you do.

$ENV{FOO} = "bla";
system('/bin/bash');

Then it spawns a new Shell and you have $FOO set there. But I don't see a point here. Just use .profile in Linux or whatever to set environment variables.

The last bit seems to my like a classical XY Problem.

CodePudding user response:

alias: test-alias not found
alias: echo not found
alias: TEST not found

This is because the correct syntax for creating an alias in sh is

alias test-alias='echo TEST'

Fixed:

system("alias test-alias='echo TEST'");

sh: 1: test-alias: not found

You still get this after fixing the first problem. You did create a shell, and you did create an alias named test-alias in it, but that shell exited. You are running test-alias; in a new shell, one in which test-alias hasn't been created.

You need to run both commands in the same shell.

Fixed:

system("alias test-alias='echo TEST'\ntest-alias");
  • Related