I am trying to send an output of an executed shell script, to a log file. However I want to put a timestamp at the start of the line for every output, so I created a function to do that. But how do I pass the results of the executed shell script, into the function?
#This is a sample of the executed file testrun.sh
#!/bin/bash
echo "Script Executed."
#Actual script being run
#!/bin/bash
testlog="/home/usr/testlog.log"
log_to_file() {
echo "$(date ' %Y-%m-%d %H:%M:%S') $1" >> $testlog
}
sh /home/usr/testrun.sh >> log_to_file
If i were to log it normally, i would just do
sh /home/usr/testrun.sh >> $testlog
But how do I pass in the output of testrun.sh, into the function log_to_file, so that I can log the output to the file with the timestamp?
CodePudding user response:
Use a while read
loop to get each line into a variable that you can pass to log_to_file
.
/home/usr/testrun.sh | while read -r line; do
log_to_file "$line"
done >> "$testlog"
You could also use the ts
command instead of your function
/home/usr/testrun.sh | ts >> "$testlog"
CodePudding user response:
You can of course do a
log_to_file "$(sh /home/usr/testrun.sh)"
Of course if your testrun.sh
produces more than one line of output, only the first one gets the timestamp as prefix.