I have this simple script to backup all my databases in postgres

    pg_dumpall -U pg_user > /tmp/tmp.txt
    echo "Dump status: $DUMP_STATUS" > /tmp/status.txt

The dump status is 0 and the tmp.txt file is properly created when the script is executed from the command line.

However, if I execute this script as a cronjob in my crontab, my tmp.txt is empty (the dump of all databases failed) and my status.txt file contains a dump status 127.

A strange behavior I noticed is that pg_dumpall will pipe the information into the file but also print it on the terminal. I'm thinking this behavior might be the cause of the problem.

Any idea how I can solve this issue?

I am running FreeBSD:

    > uname -mrs  
    FreeBSD 9.1-PRERELEASE amd64

    > psql -V
    psql (PostgreSQL) 9.1.7
    contains support for command-line editing
  • 3
    A few points: 1) you should chdir to a usefull directory or hardcode all filepaths in a cronjob. 2) PATH can be different than for a login shell. 3) the script can (and should) redirect stderr (possibly separately from stdout). 4) always start with a dummy cronjob, eg echo and date, psql select version() etc. That will get you on track wrt to path/environment errors. 5) use (or redirect) MAILTO=
    – wildplasser
    Dec 24, 2012 at 17:18
  • 2
    Normally, 127 means "command not found", so I'm with @wildplasser Dec 26, 2012 at 5:48

2 Answers 2


If the script can work apart from a crontab, you should make sure of the following:

  • The script file contains the necessary environmental variables
    • $PGHOME
    • $PGDATA
    • $PGPORT
    • $PATH
  • Output the standard error to a file for future analysis

According to http://tldp.org/LDP/abs/html/exitcodes.html a 127 code means "command not found."

As francs suggested, when you run the command normally you are implicitly relying on one or more environmental variables that exist for your login shell, but which do not exist when you run a cron job. The solution is to give absolute paths to every command.

For example, type "which pg_dumpall" in the terminal and use the resulting output where you currently have "pg_dumpall" in your scripts.

  • You guys are right. The proper environment variables were not set when the script is executed as a cronjob. This was really a silly mistake. On bash execution: PATH: /sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/sbin:/usr/local/bin:/root/bin On crontab execution: PATH: /usr/bin:/bin So the correction was this: -pg_dumpall -U pg_user > /tmp/tmp.txt +/usr/local/bin/pg_dumpall -U $PG_USER > /tmp/tmp.txt This works marvelously afterwards :)
    – Adron
    Jan 7, 2013 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.