Create log when execute a bash script?
I have created a bash script with cronjob that run everyday.
Is there any way to create a log file and see later if everything was ok? |
this is a good guide for you to read over.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html In the linux world you can redirect your stdout, stderr or even stdin in most cases to wherever you would like. The link has some examples, talks about the differences and should be enough to get you there. If you have any specific questions please let me know. |
You can either add redirection in the crontab entry, e.g.
Code:
30 8 * * * /path/to/script.sh > /path/to/file.log 2>&1 Code:
#!/bin/bash Code:
#!/bin/bash |
...also if you don't need complete execution logs you can syslog if all went OK:
Code:
# ...whatever |
I choose that option.
Code:
30 8 * * * /path/to/script.sh > /path/to/file.log 2>&1 In terminal when I type some command and execute it, if there is a error, it print it in terminal. Why actually I need stderr? |
Quote:
stderr would only be a problem with executing the script from BASH's side. So if the script was not executable it would generate a stderr saying that, however, if the script itself errors out and generates an error that it was programmed to that would actually be stdout as it is the output of the script. I hope that clarifies a bit. |
Another thing to do from inside your bash script if you wish to write your own log information; such as
Quote:
Quote:
To create a new log file Code:
echo "Daily cron job my-job.sh started." > /home/mylogin/daily-cron-ddmmyyyy.log Code:
echo "Daily cron failed to complete archive of such-and-such directory. Result: %?" >> /home/mylogin/daily-cron-ddmmyyyy.log |
I understand it now. Thank you for your explication.
What about if I want to send this log to my gmail mail? It is very difficult that? Do I need to install mail server on my machine? |
I noted that log file remember only last error or last movements. What about if I need to remember last 5 movements? Is that possible?
|
Remember that
Code:
> # creates a new file I'd go with appending the date/time to the filename as above and get the logrotate tool to auto remove the older copies. Re post #6; I'd recommend tracking stdout & stderr; you can't get those error msgs back, and the next run may not exhibit the same issue. You may also need(!) to know before the next run. Your choice though ... |
Cron automatically sends you a mail message IF there is any output to stderr or stdout.
If you want a detailed log of the commands/responses you need a "set -v" (verbose) mode for the shell. It will then output each command line as read. If you also want to know exactly what expansions the shell makes during execution, use "set -x". If you want both use "set -vx" You can also redirect stderr/stdout if you don't want a mail message (redirecting removes any output, thus cron has nothing to send...) |
All times are GMT -5. The time now is 08:39 AM. |