简体   繁体   中英

Linux shell output command to file

I run a shell script but do not get the output to my file, only the first line that echos the date is appended to the .log file. Can anyone explain why the mongodump command doesn't append to the .log file?

#!/bin/sh
DEST=/db_backups/
DAYOFWEEK=`date +%u`
echo "---------------------- $(date) -----------------------" >> mongo_backup_output.log
mongodump --archive=$DEST$DAYOFWEEK.gz --gzip >> mongo_backup_output.log

It's possibly because the output of mongodump is going to standard error rather than standard input (a) . If that's so, you can use the 2>&1 method (its position is important, it must come after the output redirection):

runSomeTask >>mongo_backup_output.log 2>&1

What this 2>&1 bit does is to send standard error (file handle 2) to the same place that standard output (file handle 1) is currently going, effectively sending both standard output and standard error to the same place.

In any case, if you want to capture the output/error of an entire script, you should be using the no-argument form of exec . This command will normally bring a new program into the process and execute it but, if you don't give it a program, it will simply modify the current one.

In other words, something like:

#!/usr/bin/env bash

exec >>mongo_backup_output.log 2>&1

# ALL output/error will now go to that file, don't have
# to explicitly redirect every single command.

DEST="/db_backups/"
DAYOFWEEK="$(date +%u)"
echo "---------------------- $(date) -----------------------"
mongodump --archive=${DEST}${DAYOFWEEK}.gz --gzip

(a) It's also possible that mongodump isn't actually generating any output but I'm going to assume you've checked this :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM