Reputation: 502
How to find out if script launched using terminal console or without, in gui by .desktop file for example?
I have look over env
output and some variables looks promising to check, like test $TERM var. But I want known for sure and a compatible/portable way to do it.
This is needed for script what will have two behaviors for user input, fallback to terminal read or gui input.
Upvotes: 3
Views: 3468
Reputation: 485
The answer by @LeonidMew is incomplete and somewhat incorrect.
You should not detect GUI by presence of STDIN (that's what [ -t 0 ] test does). There are cases when none of STDIN and GUI are available, e.g. when you run the script over ssh session in non-interactive mode. This happens often for CI deploys.
Correct answer heavily depends on your task, in general there are 4 distinct environments:
GUI is missing, STDIN is missing
.GUI is present, STDIN is missing
.GUI is missing, STDIN is present
. App can interact with user in text mode via STDIN.GUI is present, STDIN is present
.There are 2 basic tests that can help to identify the environment:
$DISPLAY env variable
.if [ -t 0 ]; ...
Combining these two test will give you the environment:
test 1 false + test 2 false: case 1 -- no user interaction available
test 1 true + test 2 false: case 2 -- interact via XWindows
test 1 false + test 2 true: case 3 -- interact via STDIN/console
test 1 true + test 2 true: case 4 -- XWindows or STDIN/console, whichever is preferred
Upvotes: 4
Reputation: 502
if [ -t 0 ]; then echo "in a terminal"; fi
That tests file descriptor 0, which is stdin. If you're launching your script as a GUI, that test should be false.
Author: glenn jackman
This won't work if the script is run from a terminal, but with input redirected. – Gordon Davisson
so for the purpose of this discussion, terminal emulator is being conflated with linux console, and both are being distinguished from a "gui method" which I'd thought xterm to be, as it opens in a gui... - JosephHarriott
Purpose of this question was writing script interface usable for text or gui if script run by .desktop shortcut or other gui method.
Upvotes: 3
Reputation: 7679
Or:
$ [ -t 0 ] && echo "in a terminal" || echo "something else"
in a terminal
Upvotes: 0