Wednesday, April 13, 2022

[SOLVED] Redirect stdout/stderr of a script to a file along with command itself and the result stderr of time command

Issue

My chain command: mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py;

  1. Redirect stdout and stderr of myscript.py to log.txt.
$ mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py 2>&1 | tee log.txt
$ cat log.txt
stdout and stderr are shown here.
  1. Insert the chain command to the beginning of log.txt.
$ echo 'mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py 2>&1' | tee log.txt | bash >> log.txt
$ cat log.txt
mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py 2>&1
stdout and stderr are shown here.
  1. Time the command
$ (time python3 mydir/myscript.py) 2> log.txt
$ cat log.txt

real    0m0,302s
user    0m0,003s
sys 0m0,001s

My question is how to concatenate 3 items above so the log.txt looks like

mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py 2>&1
stdout and stderr are shown here.

real    0m0,302s
user    0m0,003s
sys 0m0,001s

Thanks.


Solution

After some tries and errors, I think the following code is working.

(time echo 'mkdir mydir; mv myscript.py mydir/; python3 mydir/myscript.py 2>&1' | tee log.txt | bash >> log.txt) 2>> log.txt


Answered By - Lion Lai
Answer Checked By - Robin (WPSolving Admin)