per*_*ler 8 shell bash shell-scripting
我想控制这样的 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
Run Code Online (Sandbox Code Playgroud)
使用来自控制文件的参数,如下所示:
host1 user1 password1 host2 user2 password2
anotherhost1 anotheruser1 anotherpassword1 anotherhost2 anotheruser2 anotherpassword2
Run Code Online (Sandbox Code Playgroud)
其中每一行代表脚本的一次运行,其中提取了参数并制成变量。
这样做的最优雅的方式是什么?
拍
tyl*_*erl 10
对于 shell 脚本,这通常是使用source
函数来完成的,该函数将文件作为 shell 脚本执行,就像它被内联到您正在运行的脚本中一样——这意味着您在文件中设置的任何变量都会导出到您的脚本中。
缺点是 (a) 您的配置文件已执行,因此如果非特权用户可以编辑特权配置文件,则会存在安全风险。(b) 您的配置文件语法仅限于有效的 bash 语法。尽管如此,它真的很方便。
配置文件
USER=joe
PASS=hello
SERVER=127.0.0.2
Run Code Online (Sandbox Code Playgroud)
脚本文件
#!/bin/bash
# Set defaults
USER=`whoami`
# Load config values
source config.conf
foobar2000 --user=$USER --pass=$PASS --HOST=$HOST
Run Code Online (Sandbox Code Playgroud)
source
可以用一个缩写.
——所以下面两个是等价的:
source file.sh
. file.sh
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36237 次 |
最近记录: |