How check whether a program is running the terminal or in the background?

Hi I am working a go program which gives some output in two ways depending on the execution:

Now i want to determine whether the program is running in the terminal or not to decide the mode of output... is there any way in linux to determine this condition?

Currently the program is outputting in both stdout and notification, I wanted to only send the output via notification when it is invoked via keyboard shortcut. because printing to stdout when it is not running in the terminal is simply useless.


  • I would assume that when it's invoked via keyboard shortcut it is run by your desktop environment in some way and the output won't be a terminal, so you could check whether stdout is a tty or not. Based on Arkadiusz Drabczyk's answer, you could use this code:

    package main
    import (
    func main() {
            _, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
            if err != nil {
                    // Show notification here
            } else {
                    // Print to stdout here

    Note that this would also cause it to use a notification instead of stdout when it's redirected with | or >, though. If that's not good, you would have to use an explicit command line argument instead - I personally would prefer this anyway, because it clearly communicates intent and won't have surprises. You could accept an argument --notification which you add to the keyboard shortcut but don't use when invoking the tool in the command line.

    If for some reason it is inconvenient to add an argument, you could also use a symlink with a different name and check os.Args[0]. So for example, if your program is ~/bin/hello, then you'd create a "second version" called ~/bin/hello-notify which is actually just a symlink to ~/bin/hello, but in your code you check wither your os.Args[0] ends with -notify. Then you can connect the keyboard shortcut to ~/bin/hello-notify but use ~/bin/hello in the command line.