Sunday, June 5, 2022

[SOLVED] In a single script, how do I pass the output of an executed shell script, into another function?

Issue

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?


Solution

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.



Answered By - user1934428
Answer Checked By - Clifford M. (WPSolving Volunteer)