Search code examples
bashshellloggingtee

Using tee (or other command) to log errors or messages to file but only when variable x=="yes"


I tried using an if statement but this doesn't work as the tee command has the two brackets, one at the start and one at the end.

I tried something like this, which didn't work either

if [[ "$logging" == "yes" ]]; then
    ftpt="2>&1 | tee $ftpLF"
else
    ftpt="" 
fi
} "$ftpt"

Error:

./ftp.sh: line 149: syntax error near unexpected token `"$ftpt"'
./ftp.sh: line 149: `} "$ftpt"'

I use this at the moment but I have no option of turning it on/off, it's just always on

{
 ....commands....
} 2>&1 | tee "$ftpLF"

Solution

  • One option, if you can consistently quote things, is to use eval to force Bash to evaluate the added portions of the command:

    eval '{
      command1 "foo bar" baz
      command2
    } "$ftpt"'
    

    Another option would be to use an actual named function:

    ftpcommands() {
      command1 "foo bar" baz
      command2
    }
    
    if [[ "$logging" == "yes" ]]; then
        ftpcommands 2>&1 | tee "$ftpLF"
    else
        ftpcommands
    fi
    

    The latter is probably the preferred option, since you don't have to worry about weird quoting issues or other such.