1

I have a run.sh that runs many other scripts with third parties that return output. My run.sh also have some informative echo INFO ...

I would like to add something at the top of my script that log everything with the date of each command because I want to check also the speed of some of the process. I have seen that tee and scripts can do this I have tried some many time but tee is not install in the computer I am using (it is a cluster I cant easily install things) and with script I have just got

Script started, file is log.txt
Script started, file is log.txt
Script started, file is log.txt
Script started, file is log.txt
Script started, file is log.txt

EDIT:

I have figure out how to do this by

exec >logfile.txt 2>&1

But still I dont know how to add the data at the beginning of each line. And with this approach I cannot see now the output in the terminal

1
  • tee is a standard command and should be installed on all UNIX/Linux systems Jan 6, 2022 at 15:10

2 Answers 2

1

I always add a small function at the beginning of my script, "echo_do", and execute my commands through that function, as in

#! /usr/bin/ksh

echo_do () {
  echo $(date) "$@"
  eval "$@"
}

echo_do pwd
echo_do sleep 3
echo_do "ls -l /tmp | wc"
echo_do sleep 3
echo_do "find /tmp | wc"

You can also homebrew your "tee", eg. "tee.sh":

#! /usr/bin/ksh

IFS=""

if [ "X"$1 == "X-a" ]
then
  shift
else
  for OF in $@
  do
    > $OF
  done
fi

while read
do
  for OF in $@
  do
    echo "$REPLY" >> $OF
  done
  echo "<$REPLY>"
done

inserting the necessary timing wherever you feel like.

1

In a zsh script, you could do:

{
  PS4='[%D{%FT%T.%6.%z}] %N:%i> '
  set -o xtrace

  # rest of the script goes here.

} >&1 > file.log 2>&1

Which would add xtrace output including a timestamp with stdout and stderr (including the xtrace output) redirected both to the original stdout and to file.log (using some internal teeing).

You'd see something like:

$ zsh ./myscript.zsh
[2022-01-06T17:07:34.977886+0000] ./myscript.zsh:4> echo before
before
[2022-01-06T17:07:34.978244+0000] ./myscript.zsh:5> sleep 1
[2022-01-06T17:07:35.979618+0000] ./myscript.zsh:6> echo after
after

You can also set the REPORTTIME variable to 0 for zsh to output resource usage for each process that terminates (and that it waits for). By default, that includes the CPU times (user and sys) and elapsed time, but can be configured to display other resources with the TIMEFMT variable. REPORTTIME=1 to only report processes that use more than 1 second of CPU time. See also REPORTMEMORY.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .