Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
posix shell:stdout到file,exitcode到一个变量,stderr的最后一行到另一个变量_Shell_Posix_Stdout_Stderr_Exit Code - Fatal编程技术网

posix shell:stdout到file,exitcode到一个变量,stderr的最后一行到另一个变量

posix shell:stdout到file,exitcode到一个变量,stderr的最后一行到另一个变量,shell,posix,stdout,stderr,exit-code,Shell,Posix,Stdout,Stderr,Exit Code,我在POSIX shell(不是bash)中实现了以下功能: fail.sh: #!/bin/sh echo something useful echo warning 1 >&2 echo warning 2 >&2 echo an error message >&2 exit 100 该命令打印我想在stdout上使用的内容、stderr上的一些警告以及stderr上的一条错误消息,然后失败,退出代码为100 success.sh: #!/bin/

我在POSIX shell(不是bash)中实现了以下功能:

fail.sh:

#!/bin/sh
echo something useful
echo warning 1 >&2
echo warning 2 >&2
echo an error message >&2
exit 100
该命令打印我想在stdout上使用的内容、stderr上的一些警告以及stderr上的一条错误消息,然后失败,退出代码为100

success.sh:

#!/bin/sh
echo something useful
echo warning 1 >&2
echo warning 2 >&2
exit 0
此命令向stdout输出一些内容,向stderr输出一些警告,但成功完成,退出代码为0

test.sh:

#!/bin/sh -e

script=$1
rm -f success
msg=$({ $script > useful; touch success; } 2>&1 | tail -1;)

if [ -f success ]; then
        echo success
else    
        echo failure
        echo last error was: $msg
fi
在此脚本中,我希望运行这两个脚本中的任何一个,并提供以下功能:

  • 脚本的输出必须重定向到文件
  • stderr的最后一行必须保存到一个变量中,以便以后在命令未成功退出时打印最后一行
  • 我想通过检查命令的退出状态来检测命令是否成功退出
我的script test.sh实现了所有这些功能,但它使用了一个外部文件。由于我使用了
-e
,只有在
$script
成功执行的情况下,
触摸才会执行。如果不使用此技术,我是否可以捕获
$script
的退出代码


脚本必须在POSIX shell中编写,并且必须使用
-e

为什么必须使用
-e
?这是编程竞赛还是作业?@Barmar两者都不是-这是对现有shell脚本的补充,其作者坚持使用
-e
你的意思可能是
msg=$({$script>有用;}2>&1)?不,我认为不需要这种格式,所以我用更简单的形式重写了它。重定向是从左到右实现的,因此这是等效的。但是有了这个
有用的
还包含了stderrI刚刚尝试的输出
/fail.sh 2>&1>有用的
,并且
有用的
只包含了
一些有用的
。对不起,我的错误-我弄错了顺序-非常感谢您的帮助!我不知道有人能那样做!
#!/bin/sh -e

script=$1
if msg=$($script 2>&1 >useful); then
    echo success
else
    echo failure
    msg=$(echo "$msg" | tail -1)
    echo last error was: $msg
fi