0

I have a simple script creating database

#!/bin/sh
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
psql -d track -q -f "$DIR"/create.sql > RESULT
RESULT="$(psql -d track -q -f "$DIR"/create.sql)"
echo $RESULT

this:

$ bash MakeDB.sh  > result

produces empty result file

psql produces some log info that is output to terminal, the thing is I can't redirect that info, I want to pass it further as a result.

Is there a way to store psql output? It would be best if it wasn't printed in the terminal.

Wojciech Sobczyk
  • 343
  • 3
  • 12
  • This isn't relevant, but you should change `/bin/sh` to `/bin/bash` in the first line if you want the script to be executed using bash. Then you can `chmod +x` it and run it just as `./MakeDB.sh`. – Robin Green Nov 30 '13 at 12:58

1 Answers1

4

psql produces some log info that is output to terminal, the thing is I can't redirect that info, I want to pass it further as a result.

Have your script like this:

#!/bin/sh
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
psql -d track -q -f "$DIR"/create.sql > RESULT 2>&1
psql -d track -q -f "$DIR"/create.sql

You can then redirect stderr to same file as the stdout using this syntax:

bash MakeDB.sh > result 2>&1
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Unfortunately this will not work as-is as it will go into the variable, which I don't think is what is wanted. So this answer may need to be combined with http://stackoverflow.com/questions/12451278/bash-capture-stdout-to-a-variable-but-still-display-it-in-the-console – Robin Green Nov 30 '13 at 12:34
  • 1
    @RobinGreen: Oh yes good point, I missed that. But since since all OP is doing with `$RESULT` to echo it. OP can avoid storing the output in `$RESULT` and let all output/error be written to terminal. Edited it further. – anubhava Nov 30 '13 at 12:55
  • I can't invoke create.sql 2 times putting the result in a variable and then printing it would do, but RESULT is always empty – Wojciech Sobczyk Nov 30 '13 at 18:29
  • You don't need to call it twice. I just copied the script from question and that had this call twice. – anubhava Nov 30 '13 at 19:24