Search code examples
bashshellstdoutio-redirectionstderr

Error redirection in the body of the bash shell function


I have a script like the one below:

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

My goal is to redirect all outputs and errors to file err.log but unfortunately, it only prints "OK" to the log file.

Bash version is: GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

Can anybody help?


Solution

  • I suggest to swap 2>&1 and > err.log.

    From 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.