for json_config in${json_env_configurations[@]} do local keys=() local values=() while IFS= read -r key && IFS= read -r value; do keys+=("$key") values+=("$value") done < <(echo$json_config | jq -r 'to_entries[] | "\(.key)\n\(.value)"')
local log_file="$log_dir/$description" declare -A env_vars for ((i=0; i<${#keys[@]}; i++)); do key="${keys[$i]}" value="${values[$i]}" env_vars["$key"]="$value" log_file+="_${value}" done log_file+=".log"
4. 检查并关闭已有进程
确定进程占用的端口并关闭,以便为新实例的正常启动腾出资源:
1 2 3 4 5 6 7 8 9 10
for key in"${!env_vars[@]}"; do if [[ "$key" == *_PORT ]]; then port=${env_vars[$key]} pid=$(lsof -i:$port -t) if [ -n "$pid" ]; then kill -9 $pid echo"$description instance on port $port is down" fi fi done
通过lsof命令,可以识别出程序占用的端口并终止相关进程。
5. 启动服务实例
最后,针对每个环境变量启动服务实例:
1 2 3 4 5 6 7 8 9
for key in"${!env_vars[@]}"; do export"$key"="${env_vars[$key]}" done
# Start the instance eval$command > $log_file 2>&1 &
echo"$description with config $json_config is up" done
start_instances() { local description=$1 local log_dir=$2 localcommand=$3 shift 3 local json_env_configurations="$(echo "$@" | jq -c '.[]')"
# Process each JSON configuration for json_config in${json_env_configurations[@]} do # Use jq to parse the JSON string into key-value pairs local keys=() local values=() while IFS= read -r key && IFS= read -r value; do keys+=("$key") values+=("$value") done < <(echo$json_config | jq -r 'to_entries[] | "\(.key)\n\(.value)"')
# Prepare environment variables and log file name local log_file="$log_dir/$description" declare -A env_vars for ((i=0; i<${#keys[@]}; i++)); do key="${keys[$i]}" value="${values[$i]}" env_vars["$key"]="$value" log_file+="_${value}" done log_file+=".log"
# Identify and kill process based on ports for key in"${!env_vars[@]}"; do if [[ "$key" == *_PORT ]]; then port=${env_vars[$key]} pid=$(lsof -i:$port -t) if [ -n "$pid" ]; then kill -9 $pid echo"$description instance on port $port is down" fi fi done
# Export environment variables for key in"${!env_vars[@]}"; do export"$key"="${env_vars[$key]}" done
# Start the instance eval$command > $log_file 2>&1 &
echo"$description with config $json_config is up" done }