【问题标题】:Call a bash script from a perl script从 perl 脚本调用 bash 脚本
【发布时间】:2012-07-23 02:48:05
【问题描述】:

我正在尝试 perl 脚本中的代码,并且需要在 bash 中调用另一个文件。 不确定,这是最好的方法吗?我可以使用 system() 直接调用它吗? 请指导/告诉我一个示例方式。

从我到目前为止的尝试:

     #!/usr/bin/perl
     system("bash bashscript.sh");

重击:

#!/bin/bash
echo "cdto codespace ..."
cd codetest
rm -rf cts
for sufix in a o exe ; do
echo ${sufix}
find . -depth -type f -name "*.${sufix}" -exec rm -f {} \;
done

执行 perl 脚本时出现错误: 没有这样的文件或目录codetest

意外标记 `do 附近的语法错误

【问题讨论】:

标签: perl bash


【解决方案1】:

如果你只想运行你的脚本,你可以使用反引号或系统:

$result = `/bin/bash /path/to/script`;

system("/bin/bash /path/to/script");

如果您的脚本产生错误的数据量, 最好的运行方式是使用 open + pipe:

if open(PIPE, "/bin/bash /path/to/script|") {
  while(<PIPE>){
  }
}
else {
  # can't run the script
  die "Can't run the script: $!";
}

【讨论】:

  • 好答案,但是 /bin/sh 可能不是 bash,如果是 bash 将在 --posix 模式下运行。
  • 没有理由运行sh 只是为了启动bashsystem("/bin/bash", "/path/to/script");open(my $PIPE, '-|', "/bin/bash", "/path/to/script") 可以避免这种情况。
  • 也可以使用`bash script.sh`
  • @IgorChubin $! 在代码末尾有什么作用?我不熟悉 Perl。
  • @IgorChubin | 必须在`"/bin/bash /path/to/script|") 的末尾吗?那有什么作用?
【解决方案2】:

您可以使用反引号来执行命令:

$command = `command arg1 arg2`;

还有其他几种附加方法,包括 system("command arg1 arg2") 也可以执行它们。

这是一个很好的在线参考:http://www.perlhowto.com/executing_external_commands

【讨论】:

    【解决方案3】:

    您可以使用反引号、system() 或 exec。

      system("myscript.sh") == 0
        or die "Bash Script failed";
    

    另请参阅:this 帖子。

    【讨论】:

    • 无效上下文中的反引号...使用 system() 并节省一些额外的工作。
    【解决方案4】:

    我根据Why doesn't "cd" work in a bash shell script?解决了我的第一个问题:

    alias proj="cd /home/tree/projects/java"
    

    (感谢@Greg Hewgill)

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多