How to store standard error in a variable

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

    alsoUseless.sh

    This will allow you to pipe the output of your useless.sh script through a command such as sed and save the stderr in a variable named error. The result of the pipe is sent to stdout for display or to be piped into another command.

    It sets up a couple of extra file descriptors to manage the redirections needed in order to do this.

    #!/bin/bash
    
    exec 3>&1 4>&2 #set up extra file descriptors
    
    error=$( { ./useless.sh | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )
    
    echo "The message is \"${error}.\""
    
    exec 3>&- 4>&- # release the extra file descriptors
    

提交回复
热议问题