用一个外部文件的variables来控制一个bash脚本

我想要像这样控制一个bash脚本:

#!/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 

来自一个控制文件的参数如下所示:

 host1 user1 password1 host2 user2 password2 anotherhost1 anotheruser1 anotherpassword1 anotherhost2 anotheruser2 anotherpassword2 

其中每一行代表脚本的一次运行,参数被提取并作为variables。

这将是最优雅的方式呢?

使用shell脚本,通常使用source函数完成此操作,该函数将文件作为shell脚本执行,就好像它被内联到您正在运行的脚本中 – 这意味着您在文件中设置的任何variables都将导出到您的脚本中。

缺点是(a)你的configuration文件被执行,所以如果没有特权的用户可以编辑特权configuration文件,这是一个安全风险。 和(b)你的configuration文件语法被限制为有效的bash语法。 不过,这真的很方便。

config.conf

 USER=joe PASS=hello SERVER=127.0.0.2 

script.sh

 #!/bin/bash # Set defaults USER=`whoami` # Load config values source config.conf foobar2000 --user=$USER --pass=$PASS --HOST=$HOST 

source可以缩写为一个单一的. – 所以下面两个是相同的:

  source file.sh . file.sh 

像这样的东西。 重要的是使用read来获取数组。

 #!/bin/bash configfile=/pathtocontrolfile cat $configfile | while read -a HR ; do [[ -z ${HR[0]} ]] && continue # skip empty lines USER1=${HR[0]} HOST1=${HR[1]} PW1=${HR[2]} USER2=${HR[3]} HOST2=${HR[4]} PW2=${HR[5]} 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 done 

我想你应该使用像getopts的东西,如果你想使你的脚本智能化,而不是只是试图读取你的论点的数量的基础上。

像这样的东西。

 #!/bin/bash while getopts ":a" opt; do case $opt in a) echo "-a was triggered!" >&2 ;; \?) echo "Invalid option: -$OPTARG" >&2 ;; esac done $ ./go_test.sh -a -a was triggered! $ 

你也可以parsing参数。 你可以在这里阅读关于教程的更多细节。

我在这里find了工作解决scheme: https : //af-design.com/2009/07/07/loading-data-into-bash-variables/

 if [ -f "$SETTINGS_FILE" ];then . "$SETTINGS_FILE" fi