3

I have a bash script that invokes psql and executes SQL code:

sudo -i -u postgres psql <<EOF
SQL COMMANDS;
EOF 

The SQL part generates a lot of output and I'd like to redirect it to /dev/null. How does one redirect a heredoc to /dev/null ?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
ppribeli
  • 35
  • 5
  • You don't want to redirect the **heredoc**. Actually, the heredoc **is** a redirection, in that it redirects the stdin of _postgres_. You want to redirect the **output** of the _postgres_ command. This is done by `>/dev/null`. Note that this would not redirect the standard error. – user1934428 May 25 '19 at 07:53
  • Respectfully the linked question is about piping to a file; it's not clear from that answer that you can similarly deal with STDOUT and STDERR. This answer does that. – Chaim Eliyah Jan 31 '20 at 22:40

1 Answers1

4

Trivially

postgres psql <<EOF >/dev/null
  SQL COMMANDS;
EOF

The << token heredoc delimiter is just another redirection operator; so you can do stuff like

postgres psql <<EOF 2>/dev/null |
  SQL COMMANDS;
EOF
while IFS= read -r output; do
    case $output in
      *error*) printf '%s%s%s\n' "$red" "$output" "$plain";;
        *) echo "$output";;
    esac
done

where the pipeline which starts on the first line continues after the EOF token. (This requires you to have defined screen control codes for red and uncolored text separately; man tput.)

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • I don't know how postgres is producing its output, but your solution assumes, that error messages are written to stdout, not stderr, since you are throwing away stderr, which is not a good idea IMO. – user1934428 May 25 '19 at 07:56
  • Actually, I just ad libbed an example where some output from the database itself sometimes contains the text "error" which should be highlighted. Thanks for the comment; it probably can help someone better understand this. – tripleee May 25 '19 at 07:59
  • Thanks, that's what I tried but it threw an error at EOF. Then I figured out it was caused by a trailing space at EOF. – ppribeli May 26 '19 at 13:25