title: psql --(record|field)-separator NUL
body: <p>Is there some way to make <code>psql</code> separate the fields and records by <code>\0</code>, aka NUL? It's the only way to be able to pass <em>arbitrary</em> data to Bash scripts.</p>
  
  <p>Based on <a href="https://stackoverflow.com/questions/6857265/psql-recordfield-separator-nul/6867253#6867253">Matthew Wood</a>'s answer, I would expect this to print more that <code>1</code> on a newly initialized database:</p>
  
  <pre><code>declare -i count=0
  echo "\pset recordsep '\000'
  \f '\000'
  select typname from pg_type" | \
  sudo -iu postgres psql --no-align --quiet --tuples-only -d dbname -U username | while IFS= read -r -d ''
  do
      #echo "$REPLY"
      let count++
  done
  if [ -n "$REPLY" ]
  then
      #echo "$REPLY"
      let count++
  fi
  echo $count
  </code></pre>
  
  <p><strong>Workaround</strong>: Iff the <code>SELECT</code> results are unique, you can use this workaround to handle one at a time:</p>
  
  <pre><code>next_record() {
      psql --no-align --quiet --tuples-only -d dbname -U username &lt;&lt;SQL
  SELECT colname
    FROM tablename
   WHERE colname &gt; '${1}'
   ORDER BY colname
   LIMIT 1
  SQL
  }
  
  last_col=
  while true
  do
      colx="$(next_record "$last_col"; printf x)"
      if [ "$colx" = x ]
      then
          exit
      fi
      col="${colx%$'\nx'}" # The extra \n character is from psql
  
      # Do your thing here
  
      col_escaped="${col//"'"/''}" # Double single quotes
      col_escaped="${col_escaped//\\/\\\\}" # Double backslashes
      last_col="$col_escaped"
  done
  </code></pre>