2

What if I want to print every command in sh file to log file as well as console.

say for now I have below , I want single liner command (like PrintToFile ,which will print all commands outputs to file ) that can print all its preceding command output /echos to file and console #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 
2

There are two approaches. Others have mentioned tee. The second approach is the "script" command and its variants which record everything sent to the stdout of the processes. If you want the redirection in a script then use

#!/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
1

try this...

#!/bin/bash

log_file=/tmp/log.txt

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

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

You can use tee command to redirect output of your script into stdout and file.

Following command will print content of file f1.txt into file f2.txt as well as stdout (console).

cat f1.txt | tee f2.txt

For more info on tee check tee manpage

0

There's script, a program that typescripts a terminal session, i.e., logs everything that's displayed on the terminal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.