QUESTION:
Is the script running in the background, so i cannot see the echos from the script, when logged in as pi at terminal via SSH?
N.B.
Know first that the script is running - it's that the absence of the output you expected only makes it seem like it's not running.
ANSWER:
Running a script from an interactive shell (e.g. bash
is the RPi default) is different than running it from cron
.
Consider the situation when you run a script from your interactive shell in a terminal. By default the "standard output" (stdout
) and "standard error" (stderr
) generated when you run a command are sent to the TTY (or PTY) device (e.g. /dev/pts/0
) in which your interactive shell is running. This stdout
/stderr
appears in the terminal as the command/program writes it. You see it in your terminal because the interactive shell knows where to send it (e.g. /dev/pts/0
).
Now consider that same script run from cron
. There is no interactive shell, and the script has no way to know what your /dev/pts
is - if you even have one!
So what does it do with stdout
and stderr
? Answer: They are sent to /dev/null
... effectively a "black hole".
However, Linux provides a solution! It's called redirection - specifically output redirection
. You can deploy redirection in your cron
jobs very easily; following are examples:
* * * * * /usr/src/scripts/wifi_test_1.sh > /home/pi/scriptoutputs.txt 2>&1
The >
is the symbol used to specify redirection to a file with "overwrite"; i.e. each write action overwrites the file's previous contents. To "append" the outputs to the end of the file, use >>
instead of >
.
The 2>&1
is another redirection that effectively combines the stdout
(1
) with the stderr
(2
) to capture both stderr
and stdout
in the same file.
To get only the stdout
to a file:
* * * * * /usr/src/scripts/wifi_test_1.sh > /home/pi/scriptoutputs.txt
If you only want stderr
:
* * * * * /usr/src/scripts/wifi_test_1.sh 2> /home/pi/scriptoutputs.txt
What about getting cron
outputs in email?
If that's what you want - if that's useful for you - then yes, you can do that. You may configure how this works through the MAILTO
option in your crontab
:
MAILTO=
| This sends no email
MAILTO=pi
| This sends email to local user pi
[email protected]
| Requires a Gmail account & meeting Google's requirements for an "untrusted" source
IMHO, output-via-email is not a good option. If it's sent to a local user (e.g. pi
) you will have to either install a decent email client, or use the clunky default mail
utility. Sending to a real mail account requires an SMTP server - with all of the attendant hassles. But again, it can be done if this is what you need.