Add bash output to text

Asked

Viewed 167 times

1

Well, I’m trying to create a text log, with the days and times my script was executed. Only, for example: when I use echo 10/03 - 13:20 >> log.txt it overwrites there in the text file by numerical order, so it’s getting more or less like this the log:

09/01 - 10:43
10/03 - 13:20
12/03 - 12:05 

I thought about improvising and putting 1 -, 2 -, 3 - before each date, but I think it gets a lot of improvisation. Does it have any form of order other than numerical form?

  • your question is confusing...you want to sort numbers but it can’t be in numerical order ? for me it doesn’t make much sense

  • Placing the output command >> you are asking to put the content at the end of the file, ie in the last line of the text file.

1 answer

0


You can use the utility date to recover the system time and format it as needed, for example:

$ date +"%F %T"

Exit:

2019-04-22 14:20:18

To save the output of the utility to a text file without overwriting it, just concatenating the timestamp returned at the end of the file just:

$ date +"%F %T" >> log.txt

You can write a function capable of logging log events to make your life easier, for example:

function log {
    DATE=$(date +"%F %T")
    echo "[${DATE}] - ${1}" >> log.txt
}

Exemplifying:

#!/bin/bash

function log {
    DATE=$(date +"%F %T")
    echo "[${DATE}] - ${1}" >> log.txt
}

# Regista timestamp antes do processamento
log "Inicio..."

# Faz alguma coisa
sleep 1

# Registra processamento
log "Processando..."

# Faz outra coisa
sleep 1

# Regista timestamp apos o processamento
log "Terminei!"

Recorded log file:

[2019-04-22 14:31:16] - Inicio...
[2019-04-22 14:31:17] - Processando...
[2019-04-22 14:31:18] - Terminei!
  • Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.