linux 批量运行服务

以 redis 搭建集群为例,要执行 n 多次 
redis-server redis.7000.conf --daemonize yes
redis-server redis.7001.conf --daemonize yes
redis-server redis.7002.conf --daemonize yes
...

 太麻烦了,所以在 .bashrc 中,写个功能函数,能识别参数中的 [num:nmu] 替换成区间数字,批量运行:

function up(){

    if [ -z "$1" ]; then
        color green '参数: "启动命令 [开始:结束]配置文件 参数'
        color green '示例: up redis-server redis[1000:1006].conf --daemonize yes'
        return 0
    fi

    local range="$(echo "$@" | grep -o -P '\[\d+\:\d+\]' | grep -o -P '\d+')" # [1000:1006]
    range=($range)

    local i=${range[0]}
    local config=""
    local server_start=""
    while [ $i -le ${range[1]} ]; do

        server_start=$(echo "$@" | sed -r "s/\[[0-9]+\:[0-9]+\]/$i/")
        config=$(echo "$server_start" | grep -o -P "\s.*$i.*?\s" | tr -d '[:space:]')

        let i++

        if [ ! -f "$config" ]; then
            color red "$config 文件不存在 "
            continue
        fi

        color green $server_start
        $server_start

    done


}


function color() {

    local index="$1"
    shift 1
    declare -A color=([black]=30 [red]=31 [green]=32 [yellow]=33 [blue]=34)
    [ -z "${color[$index]}" ] && index='black'
    echo -e "\033[${color[$index]}m$@\033[0m"
}

测试成功,非常便捷。

posted @ 2023-05-30 17:18  心随所遇  阅读(28)  评论(0编辑  收藏  举报