share
Unix & LinuxBash Custom Log Files with Multiple Lines
[0] [1] Dennis
[2020-04-17 13:25:46]
[ bash shell-script ]
[ https://unix.stackexchange.com/questions/580699/bash-custom-log-files-with-multiple-lines ]

I have this simple bash script that looks like this:

#!/bin/sh
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP restart" /etc/init.d/nginx restart > /usr/local/nginx/logs/restart.log 2>&1

It produces the output in my restart.log like this:

2020-04-17 18:22:30 Restarting nginx (via systemctl): nginx.service. 

but the next time the script is run the output line is erased and there is just one line of the last restart instead of it. There is only one line all the time. It looks like it's just "one liner" script, not multiple lines.

Now the question is how do I make it keep all the previous entries like this:

2020-04-17 18:22:30 Restarting nginx (via systemctl): nginx.service.
2020-04-18 19:12:30 Restarting nginx (via systemctl): nginx.service.
2020-04-19 20:02:30 Restarting nginx (via systemctl): nginx.service.

I know it's supposed to be quite simple but I cannot figure it out. Would appreciate any comments / advices / suggestions. Many thanks in advance!

(5) Does this answer your question? What are the shell's control and redirection operators? - αғsнιη
Thank you so much! Yep, that did the trip! I just had to use >> instead of > - Dennis
[+1] [2020-04-17 13:47:54] Santosh Garole [ACCEPTED]

Hey You are overwriting the o/p:

Please use below to append it:

echo "$TIMESTAMP restart" /etc/init.d/nginx restart >> /usr/local/nginx/logs/restart.log 2>&1

If it works please accept the answer. - Santosh Garole
Thank you Santosh! It worked. I would've never guessed it. - Dennis
How would you like me to accept this answer, Santosh? Yes, I do accept it. Is there a button somewhere to press? I cannot see it. - Dennis
Just follow this: meta.stackexchange.com/questions/5234/… - Santosh Garole
1