perl backticks: use bash instead of sh

10,163

Solution 1

The "system shell" is not generally mutable. See perldoc -f exec:

If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp(3) with the arguments in LIST. If there is only one scalar argument or an array with one element in it, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is "/bin/sh -c" on Unix platforms, but varies on other platforms).

If you really need bash to perform a particular task, consider calling it explicitly:

my $result = `/usr/bin/bash command arguments`;

or even:

open my $bash_handle, '| /usr/bin/bash' or die "Cannot open bash: $!";
print $bash_handle 'command arguments';

You could also put your bash commands into a .sh file and invoke that directly:

my $result = `/usr/bin/bash script.pl`;

Solution 2

This example works for me:

$ perl -e 'print `/bin/bash -c "echo <(pwd)"`'
/dev/fd/63

Solution 3

To deal with running bash and nested quotes, this article provides the best solution: How can I use bash syntax in Perl's system()?

my @args = ( "bash", "-c", "diff <(ls -l) <(ls -al)" );
system(@args);
Share:
10,163
David B
Author by

David B

Updated on July 23, 2022

Comments

  • David B
    David B almost 2 years

    I noticed that when I use backticks in perl the commands are executed using sh, not bash, giving me some problems.

    How can I change that behavior so perl will use bash?

    PS. The command that I'm trying to run is:

    paste filename <(cut -d \" \" -f 2 filename2 | grep -v mean) >> filename3
    
  • David B
    David B over 13 years
    I still can't get the expected behavior. The reason I wanted bash is that I run ac command using <(grep ...) and it seems sh does not support it (but bash does). If I run my command as a user, directly from bash it works fine. If I run it from perl in backticks then sh shouts "sh: Syntax error: "(" unexpected", if I run it in backticks preceded by /usr/bin/bash I still get the same thing from sh.
  • Ether
    Ether over 13 years
    @David: I don't quite understand what command you're trying to run; can you edit that into your question with code formatting?
  • David B
    David B over 13 years
    I still get "sh: Syntax error: "(" unexpected". See a comment on the original post for the command I try to run.