====== Bash scripts can identify how they got started ====== I often develop bash scripts which I test by running them in my current terminal, and then when they're working properly (which generally just means that I haven't yet tested the situations where they break), I want to run them as a cron job. During development (and then later, once I find a situation where the script doesn't work properly), I want to have a reasonable amount of debugging output, but once the script is running as a cron job, I want it to be more or less silent. Typically, I'd do this by having a line near the top of the script which says **debug=1** while I'm developing it and just want some basic output regarding what it's doing, **debug=2** if there's a problem and I want all the detail it can give me, and **debug=0** once I think it works and I'm running it from cron. Then, throughout the script, there are various lines such as **[ "$debug" -gt 0 ] && echo ...** or **[ "$debug" -eq 2 ] && echo ...** to produce the required outputs. Wouldn't it be nice to be able to automate this, so that the script just __knows__ whether it's being run interactively, such as **./script.sh**, or perhaps over an SSH connection with **ssh rem.ote.ser.ver ./script.sh** or as a cron job, and then adjusts the debug level accordingly? Well, it turns out that you can. #!/bin/bash [ "$TERM" = "dumb" -a ! -t 0 ] && run=cron || run=local [ "`ps --no-headers o comm $PPID`" = "sshd" ] && run=SSH The variable **run** then contains one of the three values __local__, __SSH__ or __cron__ which you can use as you wish. For example: debug=0 [ "$run" = "SSH" ] && debug=1 [ "$run" = "local" ] && debug=2 Credit to https://unix.stackexchange.com/questions/46789 for insight on how to do this. ---- [[.:|Go up]]\\ Return to [[:|main index]].