Search code examples
linuxbashsedcron

Use sed to change the stdout of crontab line


I try to add datetime on stdout of my script and redirect on a file.

I use the following command:

python3 script.py 2>&1 | sed -e "s/^/$(date + \%F \%T") /" > output.log

When I add this command in crontab editor, the sed command doesn't work! Can you help me to understand the problem? Thank you in advance!


Solution

  • Looks like some quoting issues. If I'm understanding the intent correctly, I think you want this:

    python3 script.py 2>&1 | sed -e "s/^/$(date "+ %F %T")/" > output.log
    

    Within the command substitution ( $(...) ) you can have another set of quotes. It is like running the command on its own and using the output. Your original command substitution command was:

    date + \%F \%T"
    

    With the extra quote on the end, the ) is not registered as terminating the command substitution, so it actually does not terminate which is obviously a syntax error.

    I think what you were trying to do was escape the spaces which would remove the need for the extra quotes like this:

    date\ +\ %F\ %T
    

    Check out shellcheck.net for some help with syntax errors, and general advice. You can also download the program and use it directly on the terminal.