How to I test if a script is run from and interactive shell?
I have a script that can be run as a sendmail alias command, or a cron job, or run by a user. I'd like the script to know if it's being run by cron or otherwise in the background versus a user running the command at a bash prompt.
What I've found so far on the web says that if $PS1 exists, it's running from a user command line. However, I created a simple script: Code:
echo "$PS1" >/tmp/inter Code:
echo $- >/tmp/inter So, how do I do this? |
This should do the trick. The -t option checks if the given file descriptor number is a terminal.
Quote:
|
dannybpng: Nope, that doesn't work. If I type the following, manually, at the command line:
Code:
if [ -t 0 ]; then echo interactive; else echo not interactive; fi Other ideas? More info ... The bash script I put the test line in is getting stdin piped into it! That's why it comes back "not interactive". Yet I'm running it manually, at an ssh terminal session. So I need another way to figure that out. |
Quote:
|
Look at the name of the parent process.
One could test for the parent of the script in question:
Code:
ps --no-headers -p $PPID -o command |
The tests in your initial post are okay.
Code:
if [[ $- == *i* ]]; then echo interactive; else echo not interactive; fi Usually testing $PS1 is good enough: Code:
if [ -n "$PS1" ]; then echo interactive; else echo not interactive; fi |
If this code is put into a script and run from a cron job, it does work. Running this same script from the prompt still means that there is a connection with a terminal. My guess is that it will also work with sendmail, unless the user is directly interacting with the program.
Code:
if [ -t 0 ];then echo Interactive; fi |
In default ~/.bashrc there is this:
Code:
# If not running interactively, don't do anything |
Quote:
Code:
cat thisfile | testme Quote:
-bash when run manually at the command line -su when run as shown above inside the testme script at the command line /usr/sbin/crond -l notice when run from crontab (both lines) when run from crontab Quote:
Quote:
There are some environment variable differences. the piped-script-command-line has LS_COLORS set. Cron does not. TERM is "linux" for cron and "xterm" for piped/command. cron has CONSOLE set; piped/command does not. There are other, none of which seem satisfactory. I'll experiment more with test -t 2. |
You can try all of them and see whichever works:
Code:
#!/bin/sh Code:
$ ./inter |
I think the -t 2 solution will work for me. I'm going to mark that as the solution. I had no idea this would be so difficult!
|
All times are GMT -5. The time now is 03:52 AM. |