How to store standard error in a variable

后端 未结 18 2110
难免孤独
难免孤独 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:22

    Improving on YellowApple's answer:

    This is a Bash function to capture stderr into any variable

    stderr_capture_example.sh:

    #!/usr/bin/env bash
    
    # Capture stderr from a command to a variable while maintaining stdout
    # @Args:
    # $1: The variable name to store the stderr output
    # $2: Vararg command and arguments
    # @Return:
    # The Command's Returnn-Code or 2 if missing arguments
    function capture_stderr {
      [ $# -lt 2 ] && return 2
      local stderr="$1"
      shift
      {
        printf -v "$stderr" '%s' "$({ "$@" 1>&3; } 2>&1)"
      } 3>&1
    }
    
    # Testing with a call to erroring ls
    LANG=C capture_stderr my_stderr ls "$0" ''
    
    printf '\nmy_stderr contains:\n%s' "$my_stderr"
    

    Testing:

    bash stderr_capture_example.sh
    

    Output:

     stderr_capture_example.sh
    
    my_stderr contains:
    ls: cannot access '': No such file or directory
    

    This function can be used to capture the returned choice of a dialog command.

提交回复
热议问题