Home > Net >  Bash - Only When Output Is Terminal
Bash - Only When Output Is Terminal

Time:12-18

I want to have a section in my code that only executes, when the output is printed in the terminal, not piped or redirected into a text file or other program.

I tried this:

#!/bin/bash

if [[ $(tty "-s") ]]; then
  printf "You are using a terminal.\n"
else
  printf "You are not using a terminal.\n"
fi

tty -s && printf "Guten Tag.\n"

Output after ./tty.sh command:

You are not using a terminal.
Guten Tag.

Output in test.txt after `./tty.sh > test.txt`:
``` Youre not using a terminal. Guten Tag. ```

CodePudding user response:

Remember that if statements in bash checks the exit status of the provided command:

if command; then
  # then block
else
  # else block
fi

and [[ is just a special built-in command.

Simply use:

if tty -s; then

To run some code when tty -s exists with an exit status of 0, (success)

And also instead of using the tty to check if the input is a terminal, use [ -t 0 ] instead.

if [ -t 0 ]; then

See man 1 tty and man 1 test.

In case it wasn't clear from the man 1 test, then you can test if standard output and standard error output is a terminal with, respectively:

[ -t 1 ] # stdout is a terminal
[ -t 2 ] # stderr is a terminal 
  • Related