1

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. ```
theerrormagnet
  • 174
  • 2
  • 15
  • The basic syntax part here is a duplicate of https://stackoverflow.com/questions/36371221/checking-the-success-of-a-command-in-a-bash-if-statement - you are testing whether `tty -s` outputs a non-empty string, which it simply doesn't, ever. – tripleee Dec 17 '21 at 12:47

1 Answers1

1

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 
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123