How to store standard error in a variable

后端 未结 18 2114
难免孤独
难免孤独 2020-11-22 12:46

Let\'s say I have a script like the following:

useless.sh

echo \"This Is Error\" 1>&2
echo \"This Is Output\" 

And I have an

18条回答
  •  长情又很酷
    2020-11-22 13:43

    Here's how I did it :

    #
    # $1 - name of the (global) variable where the contents of stderr will be stored
    # $2 - command to be executed
    #
    captureStderr()
    {
        local tmpFile=$(mktemp)
    
        $2 2> $tmpFile
    
        eval "$1=$(< $tmpFile)"
    
        rm $tmpFile
    }
    

    Usage example :

    captureStderr err "./useless.sh"
    
    echo -$err-
    

    It does use a temporary file. But at least the ugly stuff is wrapped in a function.

提交回复
热议问题