0

I have a script that automate the rebuilding of mongo db's for our servers:

#!/bin/sh

mongo local:host 127.0.0.1 mongodb-create-ourdatabase.js > validate.txt

mongoimport --host 127.0.0.1 --db ourdatabase --collection ourUser --file create-ourUser.js > validate.txt

The output of the first line when the database is created writes to file, but the output of the second line, where the collection ourUser is created outputs to screen.

What am I missing?

richard
  • 63
  • 4

2 Answers2

0

First, both calls create an empty, new validate.txt file. So second call clobbers first call result. I doubt that this is what you want, so you should change the second > by >> to append to your logfile.

Second, executables issue output through 2 screen channels: standard output (aka stdout, used for normal output, results) and standard error (aka stderr, used for warnings and errors). It is not possible to know which stream is the target by looking at the output.

To merge both streams and get all process output, you have to pipe stderr to stdout to be able to redirect, using 2&>1 (dup & close pipe 2=stderr to 1=stdout)

mongo local:host 127.0.0.1 mongodb-create-ourdatabase.js 2&>1 > validate.txt
mongoimport --host 127.0.0.1 --db ourdatabase --collection ourUser --file create-ourUser.js 2&>1 >> validate.txt
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Thanks for the response Jean-Francois, unfortunately that did not work, but it was close. What worked was:

#!/bin/sh

mongo localhost:27017 mongodb-create-our-database.js 2>&1 > validate.txt

mongoimport --host 127.0.0.1 --db ourdatabase --collection ourUser --file create-ourUser.js >> validate.txt 2>&1

Using 2&>1 had the script looking for file 2, and I found this excellent explanation:

Scroll down to 1st answer

which worked for me.

Community
  • 1
  • 1
richard
  • 63
  • 4