Friday 27 December 2019

Determine whether a bash script was launched by icon click or from terminal


I have a script that I want to have a different behaviour depending on whether it was launched from the terminal or by (double) clicking the icon in the file manager. Can I do this?



Answer



You can use differences in the return status from tty to help you.


if tty -s;
then
# running in a terminal
...
fi

(tty -s runs the tty command silently)


Exit status:



  • 0 if standard input is a terminal

  • 1 if standard input is not a terminal

  • 2 if given incorrect arguments

  • 3 if a write error occurs


Or you could use the shell's built-in tests to check whether standard input/output are from/to a terminal:


if [ -t 0 ];  # stdin
then
# running in a terminal
...
fi

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...