【问题标题】:Error redirection in the body of the bash shell function [duplicate]bash shell函数主体中的错误重定向[重复]
【发布时间】:2022-01-13 19:44:08
【问题描述】:

我有一个类似下面的脚本:

#!/bin/bash
#func.sh 
func(){
badcommand1
echo "OK"
badcomand2
 }
func  2>&1  > err.log
#The top line is in the file

我的目标是将所有输出和错误重定向到文件 err.log 但不幸的是,它只打印 “OK”到日志文件。

Bash 版本是: GNU bash,版本 4.2.46(2)-release (x86_64-redhat-linux-gnu)

有人可以帮忙吗?

【问题讨论】:

  • 请注意,问题标题用词不当——您是在函数外部而不是内部进行重定向。

标签: bash shell stdout io-redirection stderr


【解决方案1】:

我建议交换2>&1> err.log

来自man bash

请注意,重定向的顺序很重要。例如, 命令 ls > 目录 2>&1 将标准输出和标准错误都指向文件 目录列表,而命令 ls 2>&1 > 目录 仅将标准输出定向到文件 dirlist,因为 之前从标准输出中复制了标准错误 标准输出被重定向到目录列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2012-08-17
    • 2010-10-12
    相关资源
    最近更新 更多