MacOS – Can I create a configuration file for a shell script

bashmacosshellssh

Is it possible to create a .sh shell or .command file with a configuration file?

I need to backup websites via Terminal and be able to put some data to configuration files,
and have the shell execute it.

For example, the username, password, ssh id, et cetera.

#!/bin/bash
ssh admin@host.com "tar cjvf webfilesbackup-date-`date +%Y%m%d`.tar.bz2 public_html/"    
ssh admin@host.com "mysqldump -u user_admin -ppass database_1 > databasebackup-`date +%Y%m%d`-db.sql"
scp admin@host.com:webfilesbackup-date-`date +%Y%m%d`.tar.bz2 ~/backup/
scp admin@host.com:databasebackup-`date +%Y%m%d`-db.sql ~/backup/
ssh admin@host.com "rm -f webfilesbackup-date-`date +%Y%m%d`.tar.bz2"
ssh admin@host.com "rm -f databasebackup-`date +%Y%m%d`-db.sql"

Best Answer

Create a file (e.g. settings) with your settings as variables:

username='foo'
pass='bar'
website='baz'
database='yak'

Then source the file from your script and you will be able to access the variables:

. settings
echo $username     # <- this will print "foo"

Concerning your second "question", if you have multiple hosts you can just have multiple config files and source the one passed as an argument to your script. For example, create a config file called site1.

Call your script with ./backup.sh site1

. $1               # <- this will load the file "site1"
echo $username     # <- this will print "foo"

With your backup script, this would mean:

#!/bin/bash
. $1
ssh admin@host.com "tar cjvf webfilesbackup-date-`date +%Y%m%d`.tar.bz2 public_html/"
ssh admin@host.com "mysqldump -u $user -p$pass $database > databasebackup-`date +%Y%m%d`-db.sql"
# ... and so on