Although everything can be fooled, heuristics with a good chance of success are:
- When running from the command line, input/output/stderr will be a terminal (unless redirected), and there will be a controlling terminal.
- When running as a CGI, several CGI environment variables will be set.
- When running from a shell, the SHELL environment variable will be set.
- When running as a CGI, the current UID is a dedicated user ("nobody" for instance).
- When running from a shell, there will be a home directory.
- When running as a stand-alone CGI program, the parent process will be the webserver.
- When running from the shell, the parent, or one of its ancestors will be a shell process.