0

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;
esac

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!

philippe
  • 2,303
  • 4
  • 32
  • 53

3 Answers3

1

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.

Dan Garthwaite
  • 2,962
  • 1
  • 19
  • 31
  • This would work too, but I do want have everything in my script and nothing elsewhere. Thanks for your answer! – philippe Sep 03 '13 at 18:14
0

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

Danila Ladner
  • 5,331
  • 22
  • 31
  • 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 03 '13 at 18:14
0

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.

Changaco
  • 880
  • 5
  • 10
  • 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 03 '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 03 '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 03 '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 03 '13 at 19:59