psql - save results of command to a file

后端 未结 10 1181
日久生厌
日久生厌 2020-12-12 09:10

I\'m using psql\'s \\dt to list all tables in a database and I need to save the results.

What is the syntax to export the results of a psql command to a

10条回答
  •  一整个雨季
    2020-12-12 09:46

    This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

    NOTE: For Linux servers.


    • Save the contents of your command to a file

    MODEL

    read -r -d '' FILE_CONTENT << 'HEREDOC'
    [COMMAND_CONTENT]
    
    HEREDOC
    echo -n "$FILE_CONTENT" > sqlcmd
    

    EXAMPLE

    read -r -d '' FILE_CONTENT << 'HEREDOC'
    DO $f$
    declare
        curid INT := 0;
        vdata BYTEA;
        badid VARCHAR;
        loc VARCHAR;
    begin
    FOR badid IN SELECT some_field FROM public.some_base LOOP
        begin
        select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
            into loc
            from public.some_base where some_field = badid;
            SELECT file||' '
            INTO vdata
            FROM public.some_base where some_field = badid;
        exception
            when others then
            raise notice 'Block/PageNumber - % ',loc;
                raise notice 'Corrupted id - % ', badid;
                --return;
        end;
    end loop;
    end;
    $f$;
    
    HEREDOC
    echo -n "$FILE_CONTENT" > sqlcmd
    
    • Run the command

    MODEL

    sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

    EXAMPLE

    sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

    • View/track your command output

    cat sqlop

    Done! Thanks! =D

提交回复
热议问题