如何将脚本的输出重定向到文件,而不是错误?

How to redirect the output of a script to a file, but not the error?

如果参数有效,我想将 wpa_passphrase 的输出附加到文件,否则将错误消息留在屏幕上。

我用

wpa_passphrase 1 111 2>&1 >>file
wpa_passphrase 1 111111111 2>&1 >>file

但文件仍包​​含消息,但屏幕没有:

Passphrase must be 8..63 characters

谢谢大家

问题是 wpa_passphrase 将错误写入 stdout 而不是 stderr。这段代码应该可以解决问题:

out=$(wpa_passphrase 1 1111111111) && echo "$out" >> file || echo "$out"

代码将输出分配给一个变量,并且仅当前面的命令成功时才将该变量回显到文件,否则它会将输出打印到屏幕。