Search code examples
linuxbashfileloggingstatus

Create a log in Bash Script


There's two shells scripts: A.sh and B.sh

Another script C.sh will create a log containing:

  • Host name
  • User name
  • Name of script
  • Time at which the function was executed
  • Description of function
  • Status

Example:

<My hostname>
<My username>

A.sh
12:09:00 p.m "Initialize shell" OK
12:10:00 p.m. "Creating file" OK
12:11:00 p.m. "Creating backup" FAIL

B.sh
01:00:00 p.m "Initialize shell" OK
01:01:00 p.m. "Creating file" FAIL
01:02:00 p.m. "Creating backup" FAIL

The point is to obtain the success/failure status of each function and the time at which was executed and save it all to a log file. How do I check for the status of each function in a shell?


Solution

  • 1Simplest way is flush output from scripts in independent files and then include this log files into common file, generated by C.sh. You could use tee *nix function in A.sh, B.sh to populate log files and filter only records you need. Also, it is possible to fetch errors in scripts via set +o errexit and set +o pipefail, and then check status of function executions right after the function:

    set +o errexit
    func.sh param1 param2
    if [ $? -ne 0 ] ; then
        echo "FAIL" | tee 1.txt
        exit 1 # if you need interrupt execution
    else
        echo "OK" | tee 1.txt
    fi