I would like to control a bash script like this:
#!/bin/sh
USER1=_parsefromfile_
HOST1=_parsefromfile_
PW1=_parsefromfile_
USER2=_parsefromfile_
HOST2=_parsefromfile_
PW2=_parsefromfile_
imapsync \
--buffersize 8192000 --nosyncacls --subscribe --syncinternaldates --IgnoreSizeErrors \
--host1 $HOST1 --user1 $USER1 --password1 $PW1 --ssl1 --port1 993 --noauthmd5 \
--host2 $HOST2 --user2 $USER2 --password2 $PW2 --ssl2 --port2 993 --noauthmd5 --allowsizemismatch
with parameters from a control file like this:
host1 user1 password1 host2 user2 password2
anotherhost1 anotheruser1 anotherpassword1 anotherhost2 anotheruser2 anotherpassword2
where each line represents one run of the script with the parameters extracted and made into variables.
what would be the most elegant way of doing this?
PAT
With shell scripts, this is normally accomplished using the
source
function, which executes the file as a shell script as if it was inlined into the script you're running -- which means that any variables you set in the file are exported into your script.The downside is that (a) your config file is executed, so it's a security risk if unprivileged users can edit privileged config files. And (b) your config file syntax is restricted to valid bash syntax. Still, it's REALLY convenient.
config.conf
script.sh
source
can be abbreviated with a single.
-- so the following two are equivalent:Something like this. The important bit is using read to grab a line as an array.
I found working solution here: https://af-design.com/2009/07/07/loading-data-into-bash-variables/
I think you should be using something like getopts if you want to make your script intelligent, instead of just trying to read your arguments on the number basis.
Something like this.
You can parse arguments also. You can read more details about the tutorial over here.