problem: you want to know if your bash script is being run interactively or not
This can be very useful to know, for example, if you want to programmatically determine if you should output to stdout, OR only to a log file because your script is running non-interactively.When a script is running interactively, it means a stdout is present and one can output things to stdout and the user will see them.
When a script is running non-interactively, for example when cron runs a script, stdout does not exist.
solution: check if stdout is a tty
As with so many things, there is more than one solution, but this one seems to be rock solid and very portable.As The Advanced Bash-Scripting Guide points out, for a complete test, one needs to check if stdout could be a socket too. Here is is the improved check:is_interactive() { if [ -t 1 ]; then return 0; else return 1; fi }
I hope you enjoy and have fun tuning to your needs.is_interactive() { if [[ -t 1 || -p /dev/stdout ]]; then return 0; else return 1; fi }
FYI. I tested the functions with cron and ssh on Debian squeeze (6.0.4) and bash 4.1.5.
citation:
Props to:The Advanced Bash-Scripting Guide
No comments:
Post a Comment