0

My .zshenv produces some output that is only helpful when my shell is interactive. In other cases when the shell is not interactive this output (i.e. when I run script) must be hidden.

How can I suppress .zshenv output for non-interactive shell?

P.S. I added my current solution below but it seems hackish to me.

mixel
  • 25,177
  • 13
  • 126
  • 165
  • Put the code in `.zshrc` instead of `.zshenv` if it doesn't do anything aside from produce the output. – chepner Jun 21 '17 at 21:31
  • @chepner Thanks for advice, but actually I moved the code from `.zshrc` to `.zshenv` because it sets up environment both for interactive and non-interactive shell. – mixel Jun 21 '17 at 21:40

2 Answers2

1

I added:

if [[ ! -o interactive ]]; then
    exec 1>&-
    exec 1<>/dev/null
fi

at the top of my .zshenv file to close original 1 stdout file descriptor and assign /dev/null to it.

And at the bottom I added:

if [[ ! -o interactive ]]; then
  exec 1>&0
fi

to restore it (see Reopen STDOUT and STDERR after closing them?).

mixel
  • 25,177
  • 13
  • 126
  • 165
0

My other answer does not work well in some cases.

I moved .zshenv content to a function run and added conditional redirection for this function output:

function run() {
    // .zshenv content
}

OUTPUT=1

if [[ ! -o interactive ]]; then
    OUTPUT=3
    eval "exec $OUTPUT<>/dev/null"
fi

run >& $OUTPUT

if [[ ! -o interactive ]]; then
   eval "exec $OUTPUT>&-"
fi
mixel
  • 25,177
  • 13
  • 126
  • 165