Golang : How to check if your program is running in a terminal
Problem:
Your command line application accepts inputs from a terminal only or you just want to test if the application is really running under a terminal. How to check if the application is really running under a terminal?
Solution:
Use the github.com/mattn/go-isatty package to determine if your application running under Terminal, Windows Cygwin/MSYS2.
For example, running this code ( from github.com/mattn/go-isatty ) under a terminal
package main
import (
"fmt"
"github.com/mattn/go-isatty"
"os"
)
func main() {
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println("Is Terminal")
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
fmt.Println("Is Cygwin/MSYS2 Terminal")
} else {
fmt.Println("Is Not Terminal")
}
}
will give:
Is Terminal
and if you execute the code under Gogland IDE, you will get Is Not Terminal
:
GOROOT=/usr/local/go
GOPATH=/Users/admin/go
/usr/local/go/bin/go build -i -o /private/var/folders/mt/p1knsj5x45901p6t3q0kxpq40000gn/T/Buildmaingoandrungo
/Users/admin/GoglandProjects/ReallyTerminal/main.go
/private/var/folders/mt/p1knsj5x45901p6t3q0kxpq40000gn/T/Buildmaingoandrungo
Is Not Terminal
Process finished with exit code 0
Hope this helps!
See also : Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+27.8k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+12.7k Golang : Add ASCII art to command line application launching process
+18.8k Golang : How to make function callback or pass value from function as parameter?
+5.7k Unix/Linux : Get reboot history or check when was the last reboot date
+19.8k Golang : Count JSON objects and convert to slice/array
+5.7k List of Golang XML tutorials
+17.4k Golang : Find smallest number in array
+12.1k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+17.8k Golang : Login and logout a user after password verification and redirect example
+13.1k Golang : How to calculate the distance between two coordinates using Haversine formula
+10k Golang : Setting variable value with ldflags
+5.7k Golang : Find change in a combination of coins example