Search code examples
bashshellvariablesstdoutstderr

Stdout & Stderr redirection using variables


I am trying to create 2 variables in my script to redirect error & output to file and display only the errors in the screen and other variable to to display only output in the screen. When i put it as a variable its not working. Variable is coming empty. Any help?

#!/bin/bash
timestamp="`date +%Y%m%d%H%M%S`"
displayonlyerror="2>&1 >> /tmp/postinstall_output_$timestamp.log | tee -a /tmp/postinstall_output_$timestamp.log"
displayoutput="2>&1 |tee -a /tmp/postinstall_output_$timestamp.log"

echo "No screen session found" $displayoutput
ech "No screen session found" $displayerror


Solution

  • It won't work like that, shell parses redirections before performing expansions on other tokens. Instead, define displayonlyerror and displayoutput as functions like (file is the log file name, you change it):

    displayonlyerror() {
        "$@" 2>&1 >>file | tee -a file
    }
    
    displayoutput() {
        "$@" 2>&1 | tee -a file
    }
    

    and use them like:

    displayoutput cmd args
    displayonlyerror cmd args