例如,我们要从文件Config.ini(位于当前用户的etc目录下)中获取各个配置项的值,并将之写入到NetworkInfo.txt文件中。其中,Config.ini文件的内容如下:
[network]; ip of databaseip=10.10.10.10; port of databaseport=9999
我们编写如下的shell脚本GetDatabaseConfig.sh:
#!/bin/kshCFG_FILE=$HOME/etc/Config.iniIP=` awk '$1~/[.*/{_cdr_par_=0} $0 ~ /^ *[ *network *]/ {_cdr_par_=1} $0~/^[ 11 ]*ip *=.*/ { if(_cdr_par_==1) { sub("="," "); print $2; exit 0} } ' ${CFG_FILE}`PORT=` awk '$1~/[.*/{_cdr_par_=0} $0 ~ /^ *[ *network *]/ {_cdr_par_=1} $0~/^[ 11 ]*port *=.*/ { if(_cdr_par_==1) { sub("="," "); print $2; exit 0} } ' ${CFG_FILE}`main(){ echo "ip =" $IP echo "port =" $PORT echo "[network]" >> NetworkInfo.txt echo "ip=$IP" >> NetworkInfo.txt echo "port=$PORT" >> NetworkInfo.txt echo "finish !!!!!!!!!!!"}## Execute main functionmain $*
将该脚本上传到Linux机器上,并使用“chmod 777 GetDatabaseConfig.sh”修改该脚本的权限,然后运行“./GetDatabaseConfig.sh”命令,结果如下:
ip = 10.10.10.10port = 9999finish !!!!!!!!!!!
同时,可以看到在当前目录下生成了NetworkInfo.txt文件,其内容为:
[network]ip=10.10.10.10port=9999