Score:0

Bash script output on the screen also to the log file

cn flag

I created a simple script that does a curl command ( I run it every month via crontab ) and I made it echo to a logfile with the date of run. The problem is that I want to receive the shell script output as well to the log file and I'm sure quite sure how to achieve that. This is what I have:

#!/bin/bash
#
LOGFILE=/root/Delete-Old-Indices.log
#Nginx Logs - Delete older than 90 Days
curl -XDELETE XXXXXXXXXXXXXXXXXX
echo "$(date "+%d%m%Y %T") : Starting work" >> $LOGFILE 2>&1

so now I only receive the following line of log in my log file: "Date + Time : Starting work" and I don't get the shell script output in my log file, I only see it in my shell window.

Thank you

pLumo avatar
in flag
Does this answer your question? [How to redirect output to screen as well as a file?](https://askubuntu.com/questions/38126/how-to-redirect-output-to-screen-as-well-as-a-file)
bac0n avatar
cn flag
`printf '%(%d%m%Y %T)T : %s\n' -1 "Starting work"` if you intend to print a time string `printf` is a better choice.
Score:3
cn flag

You can redirect any output to the log file the way you did for the echo command, i.e., using the >> redirection symbol.

That would cause no output to be displayed anymore on the screen. If you wish to also see the output, you can use tee with the -a or --append option, as

curl -XDELETE XXXXXXXXXXXXXXXXXX | tee -a $LOGFILE

This redirects both to the file (appending to what is already there), and the screen.

If what you want is to collect all output from the script into a log file, then simply redirect the output while invoking the shell script. Within the script itself, you would then remove all redirection.

ar flag
I was going to suggest using the redirection symbol `>>` in the `crontab` line with the bash script, but I like this solution better.
vanadium avatar
cn flag
@user68186 you are right, and that is probably more what the user wants in this specific case: running from a cron tab, one never sees the screen output. Added this to the answer
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.