在单个脚本中,如何将执行的 shell 脚本的输出传递给另一个函数?
In a single script, how do I pass the output of an executed shell script, into another function?
我正在尝试将已执行的 shell 脚本的输出发送到日志文件。
但是我想在每个输出的行的开头放置一个时间戳,所以我创建了一个函数来做到这一点。
但是如何将执行的 shell 脚本的结果传递给函数?
#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') " >> $testlog
}
sh /home/usr/testrun.sh >> log_to_file
如果我正常记录,我会做
sh /home/usr/testrun.sh >> $testlog
但是如何将 testrun.sh 的输出传递给函数 log_to_file,以便我可以将输出记录到带有时间戳的文件中?
使用 while read
循环将每一行放入一个可以传递给 log_to_file
的变量中。
/home/usr/testrun.sh | while read -r line; do
log_to_file "$line"
done >> "$testlog"
您也可以使用 ts
命令代替您的函数
/home/usr/testrun.sh | ts >> "$testlog"
你当然可以做一个
log_to_file "$(sh /home/usr/testrun.sh)"
当然,如果您的 testrun.sh
产生多行输出,则只有第一行将时间戳作为前缀。
我正在尝试将已执行的 shell 脚本的输出发送到日志文件。 但是我想在每个输出的行的开头放置一个时间戳,所以我创建了一个函数来做到这一点。 但是如何将执行的 shell 脚本的结果传递给函数?
#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') " >> $testlog
}
sh /home/usr/testrun.sh >> log_to_file
如果我正常记录,我会做
sh /home/usr/testrun.sh >> $testlog
但是如何将 testrun.sh 的输出传递给函数 log_to_file,以便我可以将输出记录到带有时间戳的文件中?
使用 while read
循环将每一行放入一个可以传递给 log_to_file
的变量中。
/home/usr/testrun.sh | while read -r line; do
log_to_file "$line"
done >> "$testlog"
您也可以使用 ts
命令代替您的函数
/home/usr/testrun.sh | ts >> "$testlog"
你当然可以做一个
log_to_file "$(sh /home/usr/testrun.sh)"
当然,如果您的 testrun.sh
产生多行输出,则只有第一行将时间戳作为前缀。