linux shell的一些技巧

先上例子:

一个文档内容:

 

[root@cong-33 ~]# cat /data/public_jdbh/sh/conf/test.json 
{
    "value1" :SERVERID,
    "value1":"NAME",
    "value1":IDNUM,
    "value1" : "TIME","GameDBUrl" : "MYSQL_USER;MYSQL_PASSWD;USER_DB;MYSQL_HOST;MYSQL_PORT",
    "LogDBUrl" : "MYSQL_USER;MYSQL_PASSWD;OTHER_DB;MYSQL_HOST;MYSQL_PORT",
}

shell脚本:

#!/bin/bash

DIRNAME=/tmp
CONFIGFILE=test.json

SERVERID=222
NAME="test"
IDNUM=333
TIME="2017-12-11 10:10:10"
MYSQL_USER="root"
MYSQL_PASSWD="123456"
MYSQL_PORT=3306
USER_DB=user
OTHER_DB=other


for OPTION in {"SERVERID","NAME","IDNUM","TIME","MYSQL_USER","MYSQL_PASSWD","USER_DB","MYSQL_HOST","MYSQL_PORT","OTHER_DB"} do sed -r -i 's@'"${OPTION}"'@'"${!OPTION}"'@g' ${DIRNAME}/${CONFIGFILE} done

 

执行:

[root@cong-33 tmp]# sh test.sh  
[root@cong-33 tmp]# cat test.json 
{
    "value1" :222,
    "value1":"test",
    "value1":333,
    "value1" : "2017-12-11 10:10:10",
    "GameDBUrl" : "root;123456;user;;3306",
    "LogDBUrl" : "root;123456;other;;3306",
}
[root@cong-33 tmp]#

 

解说:

     

for OPTION in {"SERVERID","NAME","IDNUM","TIME","MYSQL_USER","MYSQL_PASSWD","USER_DB","MYSQL_HOST","MYSQL_PORT","OTHER_DB"}
    do
        sed -r -i 's@'"${OPTION}"'@'"${!OPTION}"'@g' ${DIRNAME}/${CONFIGFILE}

##OPTION变量的内容就是 {"SERVERID","NAME","IDNUM","TIME","MYSQL_USER","MYSQL_PASSWD","USER_DB","MYSQL_HOST","MYSQL_PORT","OTHER_DB"}。这些字符串要与文档test.json中的一致。
##然后使用sed匹配到option在文档的内容,
##然后把${!OPTION} 的值替换为option的内容。
##${!OPTION}变量的值就是OPTION的值的变量的内容

 

例子2:

[root@cono-49 tmp]# a=(1 2 3 4)
[root@cono-49 tmp]# echo ${a[2]}
3[root@cono-49 tmp]# echo ${a[@]} 
1 2 3 4
[root@cono-49 tmp]# echo ${!a[@]}
0 1 2 3
[root@cono-49 tmp]# echo ${a[@]} 
1 2 3 4
[root@cono-49 tmp]# echo ${!a[@]}
0 1 2 3

 

##使用${!a[@]} 可以得到数组的下标

 

 


 

posted @ 2017-12-08 11:57  LYCong  阅读(718)  评论(0编辑  收藏  举报