bash shell 函数体中的错误重定向

Error redirection in the body of the bash shell function

我有一个如下所示的脚本:

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

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

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

有人可以帮忙吗?

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

来自man bash

Note that the order of redirections is significant. For example,
the command

ls > dirlist 2>&1

directs both standard output and standard error to the file
dirlist, while the command

ls 2>&1 > dirlist

directs only the standard output to file dirlist, because the
standard error was duplicated from the standard output before
the standard output was redirected to dirlist.