What I want:
There is a file /scripts/backup/config.cfg
which contains variables. In my specific case the important ones are:
BACKUPLOCATION="" ROOTLOCATION="/backup"
Then there is a script /scripts/backup/performBackup.sh
For a specific reason I want a part of the script do the following operations:
- read the value of the variable
ROOTLOCATION
- add a (“/” and) timestamp (Date&Time)
- safe the new created value to
BACKUPLOCATION
(by replacing its current value)
Example
If this is the previous state of the config.cfg
:
BACKUPLOCATION="dummy" ROOTLOCATION="/backup"
After the script ran it should be:
BACKUPLOCATION="/backup/2020-05-02-23-00" ROOTLOCATION="/backup/"
What I tried
First of all the config file gets “loaded” using
source /scripts/backup/config.cfg
I then tried to use the sed
command but the quotes are messing with me. Here is one try (which didn’t work):
sed -i 's/BACKUPLOCATION=.*/BACKUPLOCATION="'$ROOTLOCATION/$(date +%Y-%m-%d-%H-%M)'"/' /scripts/backup/config.cfg
Advertisement
Answer
Try this:
source /scripts/backup/config.cfg sed -i 's|BACKUPLOCATION=.*|BACKUPLOCATION="'"$ROOTLOCATION/$(date +%Y-%m-%d-%H-%M)"'"|' /scripts/backup/config.cfg
The problem with your sed is that you use /
as delimiter, which is present in $ROOTLOCATION
after expansion, therefore sed fails. I used |
, which is usually is not present in filenames. If you ever create a file with |
, that sed will fail too! So, “know your data” 🙂