perl から外部コマンドを実行すると sh で起動してしまうため、bash を指定してコマンドを実行する方法を調べてみました。
system 関数で bash を使いたい場合、「bash -c」を明示的に指定してコマンドを実行することができます。
#!/usr/bin/perluse 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;}
「qx//」 でも同様に 「bash -c」 を使うことで、bash シェルを指定してコマンドを実行できます。
#!/usr/bin/perluse strict;use warnings;# Bashを使ってコマンドを実行し、その結果をキャプチャmy$output =qx(bash -c 'echo Hello from bash && ls -l /home');# 出力を表示print"Command output:\n$output";
#!/usr/bin/perluse strict;use warnings;# Bashを使ってコマンドを実行し、その結果をキャプチャmy$output =`bash -c 'echo Hello from bash && ls -l /home'`;# 出力を表示print"Command output:\n$output";
open 関数を使って外部コマンドの実行結果をパイプとして読み込む場合も、bash -c を指定して実行できます。
#!/usr/bin/perluse strict;use warnings;# Bashを使ってコマンドを実行し、結果をパイプとして取得open(my$fh,'-|','bash','-c','ls -l /home')ordie"Could not execute command:$!";# 出力を1行ずつ処理while (my$line = <$fh>) {print"Output:$line";}close($fh);
引用をストックしました
引用するにはまずログインしてください
引用をストックできませんでした。再度お試しください
限定公開記事のため引用できません。