如果我想将 sh 文件中的每个命令打印到日志文件和控制台怎么办

如果我想将 sh 文件中的每个命令打印到日志文件和控制台怎么办

如果我想将 sh 文件中的每个命令打印到日志文件和控制台该怎么办?

现在我有下面的内容,我想要单行命令(例如打印到文件,这会将所有命令输出打印到文件 ) 可以将所有前面的命令输出 /echos 打印到文件和控制台 #sh

SH
**some command here, so it will print all below echos to file and console** 

echo start
echo "My first name is $1"
echo "My surname is $2"
echo "Total number of arguments is $#" 
echo end 

答案1

有两种方法。其他人提到了T恤。第二种方法是“script”命令及其变体,它记录发送到进程标准输出的所有内容。如果您想在脚本中进行重定向,请使用

#!/bin/bash
{
echo start
echo "My first name is $1"
echo "My surname is $2"
echo "Total number of arguments is $#"
echo end
} | tee logfile

答案2

尝试这个...

#!/bin/bash

log_file=/tmp/log.txt

function log(){
echo "$@" | tee -a "${log_file}"
}

log "test"
log "hello"
log "testing...."

答案3

您可以使用tee命令将脚本的输出重定向到标准输出和文件。

以下命令将把文件 f1.txt 的内容打印到文件 f2.txt 以及 stdout(控制台)中。

cat f1.txt | tee f2.txt

有关 T 恤检查的更多信息T 恤联机帮助页

答案4

script一个程序可以对终端会话进行打字,即记录终端上显示的所有内容。

相关内容