Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a bash script tell if it's being run via cron?

Tags:

bash

cron

Not having much luck Googling this question and I thought about posting it on SF, but it actually seems like a development question. If not, please feel free to migrate.

So, I have a script that runs via cron every morning at about 3 am. I also run the same scripts manually sometimes. The problem is that every time I run my script manually and it fails, it sends me an e-mail; even though I can look at the output and view the error in the console.

Is there a way for the bash script to tell that it's being run through cron (perhaps by using whoami) and only send the e-mail if so? I'd love to stop receiving emails when I'm doing my testing...

like image 789
Topher Fangio Avatar asked Jul 09 '10 17:07

Topher Fangio


People also ask

How do I know if crontab is running a script?

You can find them in /var/spool/cron/crontabs. The tables contain the cron jobs for all users, except the root user. The root user can use the crontab for the whole system. In RedHat-based systems, this file is located at /etc/cron.

How do I know if a process is running bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do I know if cron daemon is running?

To check to see if the cron daemon is running, search the running processes with the ps command. The cron daemon's command will show up in the output as crond. The entry in this output for grep crond can be ignored but the other entry for crond can be seen running as root. This shows that the cron daemon is running.

Does cron run in a shell?

Cron is a system that helps Linux users to schedule any task. However, a cron job is any defined task to run in a given time period. It can be a shell script or a simple bash command. Cron job helps us automate our routine tasks, it can be hourly, daily, monthly, etc.


2 Answers

you can try "tty" to see if it's run by a terminal or not. that won't tell you that it's specifically run by cron, but you can tell if its "not a user as a prompt".

you can also get your parent-pid and follow it up the tree to look for cron, though that's a little heavy-handed.

like image 129
eruciform Avatar answered Oct 08 '22 22:10

eruciform


I had a similar issue. I solved it with checking if stdout was a TTY. This is a check to see if you script runs in interactive mode:

if [ -t 1 ] ; then      echo "interacive mode"; else     #send mail fi 

I got this from: How to detect if my shell script is running through a pipe?

The -t test return true if file descriptor is open and refers to a terminal. '1' is stdout.

like image 43
shekwi Avatar answered Oct 08 '22 21:10

shekwi