重定向输出和错误到功能 [英] Redirect stdout and stderr to Function

查看:110
本文介绍了重定向输出和错误到功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助把从系统命令到一个bash函数的输出(stdin和stdout),同时还从参数接受输入。像下面的例子。有人能指出我下了正确的道路?

  LogMsg()
{
  日期时间=`日期+%Y /%M /%D%H:%M:%S`
  呼应*****$日期时间'('$ QMAKESPEC'):'$ 1>> $日志文件
  回声$日期时间'('$ QMAKESPEC'):'$ 1
}#已经工作
LogMsg这句话直接发送#希望我能做到这一点:
#捕获标准输出和放大器;系统功能的标准错误到日志文件
#我不presume任何以下语法是好的
使2 - ;&放大器1为卤素;(LogMsg)


解决方案

要做到这一点,你可以使用的 bash的内置

  LogMsg()
{
  阅读#这读取标准输入并存储一个字符串在一个名为变量
  日期时间=`日期+%Y /%M /%D%H:%M:%S`
  呼应*****$日期时间'('$ QMAKESPEC'):'$ IN>> $日志文件
  回声$日期时间'('$ QMAKESPEC'):'$ IN
}

然后用管道:

 使2  - ;&放大器; 1 | LogMsg

更新:

要能够使用标准输入或参数作为输入(按chepner的评论),你可以这样做:

  LogMsg()
{
  如果[-n$ 1]
  然后
      IN =$ 1
  其他
      阅读#这读取标准输入并存储一个字符串在一个名为变量
  科幻  日期时间=`日期+%Y /%M /%D%H:%M:%S`
  呼应*****$日期时间'('$ QMAKESPEC'):'$ IN>> $日志文件
  回声$日期时间'('$ QMAKESPEC'):'$ IN
}

I need help sending the output (stdin and stdout) from system commands to a bash function, while still accepting input from arguments. Something like the example that follows. Can someone point me down the right road?

LogMsg()
{
  DateTime=`date "+%Y/%m/%d %H:%M:%S"`
  echo '*****'$DateTime' ('$QMAKESPEC'): '$1 >> "$LogFile"
  echo $DateTime' ('$QMAKESPEC'): '$1
}

# Already works
LogMsg "This statement is sent directly"

# Wish I could do this:
# Capture both stdout & stderr of a system function to the logfile
# I do not presume that any of the syntax that follows is good
make 2>&1 >(LogMsg)

解决方案

To do this you can use the read bash builtin:

LogMsg()
{
  read IN # This reads a string from stdin and stores it in a variable called IN
  DateTime=`date "+%Y/%m/%d %H:%M:%S"`
  echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile"
  echo $DateTime' ('$QMAKESPEC'): '$IN
}

And then use a pipe:

make 2>&1 | LogMsg

Update:

To be able to use stdin OR an argument as input (as per chepner's comment) you can do this:

LogMsg()
{
  if [ -n "$1" ]
  then
      IN="$1"
  else
      read IN # This reads a string from stdin and stores it in a variable called IN
  fi

  DateTime=`date "+%Y/%m/%d %H:%M:%S"`
  echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile"
  echo $DateTime' ('$QMAKESPEC'): '$IN
}

这篇关于重定向输出和错误到功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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