linux shell的一些技巧
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux shell的一些技巧相关的知识,希望对你有一定的参考价值。
先上例子:
一个文档内容:
[[email protected]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 ‘[email protected]‘"${OPTION}"‘@‘"${!OPTION}"‘@g‘ ${DIRNAME}/${CONFIGFILE} done
执行:
[[email protected]33 tmp]# sh test.sh [[email protected]-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", } [[email protected]-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 ‘[email protected]‘"${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:
[[email protected]49 tmp]# a=(1 2 3 4) [[email protected]-49 tmp]# echo ${a[2]} 3[[email protected]-49 tmp]# echo ${a[@]} 1 2 3 4 [[email protected]-49 tmp]# echo ${!a[@]} 0 1 2 3 [[email protected]-49 tmp]# echo ${a[@]} 1 2 3 4 [[email protected]-49 tmp]# echo ${!a[@]} 0 1 2 3
##使用${!a[@]} 可以得到数组的下标
以上是关于linux shell的一些技巧的主要内容,如果未能解决你的问题,请参考以下文章