English 中文(简体)
在bash中使用tee时如何返回错误代码
原标题:How to return error code when using tee in bash

我想使用tee任何命令(第一个命令)的输出写入文件,但我想从第一个命令而不是te命令获得返回代码。

示例1:以下代码将返回1,并且它是预期的:

cp -unknown-args "hello"
echo "return code is $?"

---output---
cp: invalid option --  k 
Try  cp --help  for more information.
return code is 1

示例2:以下代码将返回0,这是意外的:

cp -unknown-args "hello" | tee test.txt
echo "return code is $?"

---output---
cp: invalid option --  k 
Try  cp --help  for more information.
return code is 0

I want to make "Example 2" to return 1 if the first command has any error. Is it possible and how to do if yes?

问题回答

尝试<code>set-o pipefail</code>,这将把非零出口传播到以后的管道成员





相关问题
Signed executables under Linux

For security reasons, it is desirable to check the integrity of code before execution, avoiding tampered software by an attacker. So, my question is How to sign executable code and run only trusted ...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

How to write a Remote DataModule to run on a linux server?

i would like to know if there are any solution to do this. Does anyone? The big picture: I want to access data over the web, using my delphi thin clients. But i´would like to keep my server/service ...

How can I use exit codes to run shell scripts sequentially?

Since cruise control is full of bugs that have wasted my entire week, I have decided the existing shell scripts I have are simpler and thus better. Here is what I have so far svn update /var/www/...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

热门标签