monk
monk

Reputation: 2115

Append dynamic timestamp at the start of command output

I wanted to check with bash community if its possible to print dynamic timestamp before each line of command output, even the command itself take sometime to print the entire result. Here is example:

Here , for sake of explanation assume (echo hi; sleep 10; echo hello) as a single CLI command. It will print the entire result in ~10 seconds(this could varies) which comprises of multiple line output, note the output below . Every line is having exact timestamp when the line is printed to the screen.

(echo hi ;sleep 10 ;echo hello) |perl -nle 'print scalar(localtime), " ", $_'
Mon Oct 15 13:15:57 2018 hi
Mon Oct 15 13:16:07 2018 hello

Query:

So, my question: Is is possible to manipulate bashrc or any other configuration in such a way that this will become default behavior without using pipe and perl command manually on each command ?

Upvotes: 0

Views: 328

Answers (1)

Socowi
Socowi

Reputation: 27215

For simplicity, I replaced your perl command by ts. The following trick is not a full solution, but you may be interested anyway.

Start bash | ts manually, in the new shell all command outputs will be timestamped. Example of such an interactive session:

$ echo test
test
$ bash | ts
$ echo test
Oct 16 13:40:16 test
$ for i in a b c; do echo "$i"; sleep 1; done
Oct 16 13:41:38 a
Oct 16 13:41:39 b
Oct 16 13:41:40 c
$ exit
Oct 16 13:41:51
$ echo test
test

However, text interfaces like that of nano do not seem to work anymore when inside bash | ts. Also clearing the scroll buffer with printf '\033c' doesn't work anymore.

The following command will start bash | ts from within your .bashrc. Paste it at the very end of .bashrc. I wouldn't recommend it because of the mentioned problems.

bashParents="$(ps | grep -Fwc bash)"
(( bashParents-- )) # because of subshell $(...)
if (( bashParents <= 1 )); then
    bash | ts
fi

Upvotes: 1

Related Questions