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!

3 Answers 3

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.

4
  • 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. Sep 3, 2013 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, 2013 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. Sep 3, 2013 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, 2013 at 19:59
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.

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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