Background shell script

I have a friend at work that asked me a question today and I figured I would seek help here. How does a shell script know whether it is running in the background or not?

Thanks in advance for help

There is no reliable way to determine your foreground/background status. But suppose for a minute that there was a way. It would still not be reliable. A job control shell can move a process between background and foreground at will. So if the script somehow determines which it is, it could change before the next instruction of the script is executed.

Maybe I dont understand the actual definition of background or foreground but you explanation could hold true if this script was executed via cron?

I apologize if I am sounding like a newbie, but I am :slight_smile:

If it's executed via cron, it is neither background nor foreground. From your prompt type:
sleep 30
This sleep command is in the foreground because your shell is waiting for it to finish before it will issue another prompt. Now type the command:
sleep 30 &
This sleep command is in the background because your shell issued another prompt without waiting for it to complete.

yeah I actually tried that and went to see "ps" to see if I might see something there that would lead me in the right direction. But as you already know I had no luck. OK I just wanted to get a better understanding of how it all worked so thats why I took on the challenge. Thanks for your help.

You can use the tty command to see if the standard input is a terminal. If not, then the script is running under cron/batch/at (or it is backgrounded with a nohup and the user has logged out). If the standard input is a terminal, then this method doesn't tell you the foreground/background status.