Bash variable assignment using another variable as part
I have the following excerpt from a bash script used to backup a database
#!/bin/bash
DB=database_name
DBUSER=username
FILENAME=$DB_$(date +%s).sql
I am trying to reuse the value of DB
within the FILENAME
variable assignment, but it won't let me use substitution this way. I just get the timestamp for the file name.
Is it possible to achieve what I want, and if so what is the syntax?
thanks.
Solution 1:
The problem is that bash
does not know that you mean $DB
instead of $DB_
(which is a perfectly valid name for a variable).
The best option is to be explicit on the name of the variable using braces around its name:
FILENAME=${DB}_$(date %s).sql
This saves you the trouble of escaping other characters which are not to be interpreted as part of a variable name.
Solution 2:
Alternately, use braces to isolate your variable. I think it's a bit clearer than putting quotes in there.
FILENAME=${DB}_$(date +%s).sql