I want my cron scripts being executed verbosly when run interactively by a system user (for debug purpose for instance) and quietly otherwise (for cron, as I want receive e-mail if and only if I get errors).

I have tried this in my script:

case "$-" in
*i*) echo "this shell is interactive" > /tmp/log;
*) echo "this shell isn't" > /tmp/log;

but even when run interactively (/bin/bash /tmp/my_script.sh) it returns always "this shell isn't" and

echo $-

in shell script returns hB and not hiB.

I have also tried

if [ -z $PS1 ]

thinking that cron does not have $PS1 set, but once again, from prompt, echo $PS1 returns this variable, and interactively in a script, it returns nothing :/

I would like to know why interactively (/bin/bash my_script.sh) this does not return the i value for $- nor the value of $PS1.

Many thanks for your help!


You could check if stdin is a tty.

Alternatively you could add a flag to your script telling it to be quiet or verbose instead of making it guess.

  • I would like to know why interactively (/bin/bash my_script.sh) this does not return the i value for $- nor the value of $PS1. This is not the answer for that question. – Danila Ladner Sep 3 '13 at 18:19
  • @DanilaLadner Calling bash my_script.sh doesn't invoke an interactive shell, you need to pass it the -i flag. $PS1 isn't set because a non-interactive shell doesn't load the bashrc files that define it. – Changaco Sep 3 '13 at 18:32
  • did you read my answer to his question? even if you pass "-i" argument, it won't have a terminal, if someone does it in the script, it means they do not know what they are doing. – Danila Ladner Sep 3 '13 at 18:47
  • @DanilaLadner Being interactive and "having a terminal" are two different things. If you pass -i to the shell then i will be in the value of $-, and $PS1 will be set, even if the script isn't executing in a terminal. – Changaco Sep 3 '13 at 19:59

You could set an environment variable in cron, and check for that.

Put THISISCRON=1 on a line on its own above the cron entry.

  • This would work too, but I do want have everything in my script and nothing elsewhere. Thanks for your answer! – philippe Sep 3 '13 at 18:14

Bash scripts never have interactive option on. They are non-interactive everywhere.

  • Indeed, even when you specify -i or -l in the shebang, it is still noninteractive when it is acting as a script interpreter. – Falcon Momot Sep 3 '13 at 18:14

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.