Skip to main content
Jun 10, 2017

Every advanced GNU/Linux user uses Bash scripts to make life easier.

We maintenance a lot of websites, hosted mostly on LAMP systems (Linux, Apache, MySQL, PHP). Tasks could be time consuming if you have so many sites, so creating scripts to done jobs instead of you is very useful.

One of tasks that all webmasters need to do is to backup files and databases. We have our own scripts that regularly backup and compress websites and use current date to create filenames.

Using more than one variable to create a file name in a Bash script could be tricky if the file name contain any other regular characters (dash, underscore...)

Let's say that we need to create a database backup using the following script:

DATE=$(date -I)
DBNAME="database"
USER="username"
PASS="password"
mysqldump -u $USER -p$PASS $DBNAME | gzip -9 > /backup/$DBNAME_$DATE.sql.gz

Contrary to expections, result backup name will not contain $DBNAME variable's value, i.e. the name will be, for example, 2011-08-23.sql.gz instead of exptected database_2011-08-23.sql.gz.

Since _ is a valid character in a variable name you have to separate it from db name. This can be done in several ways, e.g. using quotes or brackets to avoid any variable substitution issues.

${DBNAME}_${DATE}.sql.gz

or

"$DBNAME"_"$DATE".sql.gz

So, the final valid sample script could looks like:

DATE=$(date -I)
DBNAME="database"
USER="username"
PASS="password"
mysqldump -u $USER -p$PASS $DBNAME | gzip -9 > /backup/"$DBNAME"_"$DATE".sql.gz