如何获取错误输出并将其存储在变量或文件中 [英] How to get error output and store it in a variable or file

查看:82
本文介绍了如何获取错误输出并将其存储在变量或文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何获取错误输出并将其存储在ksh的变量或文件中时遇到了一些麻烦.因此,在我的脚本中,我在while循环中包含了cp -p source.file destination.

I'm having a little trouble figuring out how to get error output and store it in a variable or file in ksh. So in my script I have cp -p source.file destination inside a while loop.

出现以下错误

cp: source.file: The file access permissions do not allow the specified action.

我想获取它并将其存储在变量或文件中.

I want to grab it and store it in a variable or file.

谢谢

推荐答案

您可以像这样重定向命令的错误输出:

You can redirect the error output of the command like so:

cp -p source.file destination 2>> my_log.txt

它将错误消息附加到my_log.txt文件中.

It will append the error message to the my_log.txt file.

如果需要变量,可以将stderr重定向到stdout并将命令输出分配给变量:

In case you want a variable you can redirect stderr to stdout and assign the command output to a variable:

my_error_var=$(cp -p source.file destination 2>&1)

这篇关于如何获取错误输出并将其存储在变量或文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆