4

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?

  • You should use set -eu at the beginning of all your shell scripts. set -u causes an error when an unbound variable such as FILE_error is encountered. set -e makes the program exit if anything fails. – Martin Jambon May 10 at 19:56
6

A very common mistake:

ERROR_FILE="$HOME/pg_bak/error_bak/${FILE}_error.txt"
4

As jlliagre pointed out you need to use braces around the part of the string you want bash to treat as a variable name. Otherwise it will only stop treating the string as the name when it gets to a character that can't be part of the name.

In this case FILE_error is being treated as the name of the variable because _ is allowed in variable names. You actually only want the FILE part, so you have to tell bash that specifically by putting braces around that part as ${FILE}_error.

In your example FILE_error was never set, so it expands to an empty string, so you get just .txt as the filename.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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