如何在'if'中打印命令?

时间:2013-06-25 17:35:47

标签: bash shell unix zsh

if  g++ test.cpp > /dev/null 2>&1
then
    ./a.out
else
    g++ test.cpp
fi

如果gcc没有返回任何错误,我正在编写一个shell脚本来运行,否则会打印错误。如何在不编译代码的情况下打印错误?

2 个答案:

答案 0 :(得分:3)

嗯,最简单的事情是:

if g++ test.cpp > /tmp/some_temp_file 2>&1
then
    ./a.out
else
    cat /tmp/some_temp_file
fi
rm /tmp/some_temp_file

答案 1 :(得分:2)

如果通过打印错误表示只有stderr的输出,那么你可以这样做

g++ test.cpp >/dev/null && ./a.out

但是,更一般地说,将输出重定向到文件,如在depesz'回答,是最简单的方法,它也为您提供了操作输出的能力,因为您认为适合您自己的目的。任何其他技巧都可能存在可移植性问题,但请记住,重定向可能由于其自身原因而失败(文件不可写,磁盘上没有剩余空间等)。