I wrote the following shell script for a pg backup:
#!/bin/bash
PG_USER=donato
DATABASE=mydb
SERVER=216.58.219.174
DIR="$HOME/pg_bak"
DATE=$(date +"%m_%d_%y")
FILE="$DATABASE_$DATE"
ERROR_FILE="$HOME/pg_bak/error_bak/$FILE_error.txt"
# pass @ .pgpass
PG_BAK_NOW () {
pg_dump -h $SERVER -U $PG_USER $DATABASE >$FILE 2>$ERROR_FILE
code=$?
if [ $code -ne 0 ]; then
echo 1>&2 "The backup failed (exit code $code), check for errors in $ERROR_FILE"
fi
}
echo "Ready to dump to $FILE" >> "$HOME/pg_status"
cd $DIR
if [ -f "$FILE" ];
then
rm $FILE
PG_BAK_NOW
else
PG_BAK_NOW
fi
When I execute it, I know it executes for a bit of time:
$ pgrep -fl pg_bak.sh
4603 pg_bak.sh
But then it does crash:
$ ./pg_bak.sh
The backup failed (exit code 1), check for errors in /home/viggy/pg_bak/error_bak/.txt
Notice the .txt
part. The name of the error file was supposed to be mydb_6_11_2016_error.txt
, not .txt
. Why did the bash script not interpolate the variable $FILE and the hardcoded string "_error"? It did interpolate $FILE in the dump file correctly, but not the error file. Why?
set -eu
at the beginning of all your shell scripts.set -u
causes an error when an unbound variable such asFILE_error
is encountered.set -e
makes the program exit if anything fails.