I want to use bash instead of sh when I use the open function. For instance:
sub run_cmd {
my ($cmd) = @_;
my $fcmd;
print("Run $cmd\n");
open($fcmd, "$cmd |");
while ( my $line = <$fcmd> ) {
print "-> $line";
}
close $fcmd;
}
eval{run_cmd('ps -p $$')};
Here, the output is:
Run ps -p $$
-> PID TTY TIME CMD
-> 189493 pts/6 00:00:00 sh
We can see sh is used by default.
I have some constraints and I need (1) to use the open function and (2) to call bash instead of sh. I tried simply to add bash at the beginning of my command but it doesn't work:
Run ps -p $$
/bin/ps: /bin/ps: cannot execute binary file
What can I do to use bash with the open function?
You can explicitly run bash instead.
open($fcd, "bash -c '$cmd' |");
The other answer indeed shows some important best practices for when cmd is not completely trivial, or not under your control.
Don't take your chances with quote injections:
open my $fcmd, '-|', qw(bash -c), $cmd;
(Also notice that you don't need to close $fcmd explicitly if you declared it with my; it will be automatically closed at the end of the block; perl is not java ;-))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With