ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【perl】外部コマンドでシェルを指定する方法

perl から外部コマンドを実行すると sh で起動してしまうため、bash を指定してコマンドを実行する方法を調べてみました。

方法1: 「system」関数で 「bash -c」を使用

system 関数で bash を使いたい場合、「bash -c」を明示的に指定してコマンドを実行することができます。

#!/usr/bin/perl
use strict;
use warnings;

# Bashを使ってコマンドを実行
system("bash", "-c", "echo Hello from bash && ls -l /home");

# エラーチェック
if ($? == -1) {
    print "failed to execute: $!\n";
} elsif ($? & 127) {
    printf "child died with signal %d, %s coredump\n",
           ($? & 127),  ($? & 128) ? 'with' : 'without';
} else {
    printf "child exited with value %d\n", $? >> 8;
}

方法2: 「qx//」 で 「bash -c」 を使用

「qx//」 でも同様に 「bash -c」 を使うことで、bash シェルを指定してコマンドを実行できます。

#!/usr/bin/perl
use strict;
use warnings;

# Bashを使ってコマンドを実行し、その結果をキャプチャ
my $output = qx(bash -c 'echo Hello from bash && ls -l /home');

# 出力を表示
print "Command output:\n$output";

方法3: バックスラッシュ で 「bash -c」 を使用

#!/usr/bin/perl
use strict;
use warnings;

# Bashを使ってコマンドを実行し、その結果をキャプチャ
my $output = `bash -c 'echo Hello from bash && ls -l /home'`;

# 出力を表示
print "Command output:\n$output";

方法4: open 関数で bash を使用

open 関数を使って外部コマンドの実行結果をパイプとして読み込む場合も、bash -c を指定して実行できます。

#!/usr/bin/perl
use strict;
use warnings;

# Bashを使ってコマンドを実行し、結果をパイプとして取得
open(my $fh, '-|', 'bash', '-c', 'ls -l /home') or die "Could not execute command: $!";

# 出力を1行ずつ処理
while (my $line = <$fh>) {
    print "Output: $line";
}

close($fh);