#!/usr/bin/env bash
# 创建不存在的topic
list_topic(){
local host_ip=$1
$KAFKA_HOME/kafka-topics.sh --bootstrap-server $host_ip:10180 --list > topics.txt
# 使用readarray将文件内容读入数组
readarray -t lines < topics.txt
export all_topics=("${lines[@]}")
}
delete_topic(){
local topic=$1
local host_ip=$2
$KAFKA_HOME/kafka-topics.sh --bootstrap-server $host_ip:10180 --delete --topic $topic
echo "topic $topic already deleted"
}
create_topic(){
local topic=$1
local host_ip=$2
$KAFKA_HOME/kafka-topics.sh --create --bootstrap-server $host_ip:10180 --topic $topic --partitions 1 --replication-factor 1
echo "topic $topic already created"
}
function main(){
host_ip=$(ifconfig | grep -oP 'inet (?:addr:)?\K([0-9]{1,3}\.){3}[0-9]{1,3}' | grep -v '127.0.0.1' | head -n 1)
KAFKA_HOME="/home/kafka/kafka_2.13-3.4.0/bin"
topic_array=(
"topic1"
"topic2"
"topic3"
"topic4"
"topic5"
)
list_topic $host_ip
# 将数组转为文件
echo "${topic_array[@]}" | tr ' ' '\n' > array1.txt
echo "${all_topics[@]}" | tr ' ' '\n' > array2.txt
# 找出arr1中不在arr2中的元素
grep -Fxv -f array2.txt array1.txt > array3.txt
# 读取结果到新数组
readarray -t arr3 < array3.txt
# 清理临时文件
rm -f array*
# 输出结果
echo "below kafka topics need to be created :"
printf "%s\n" "${arr3[@]}"
# 使用for循环遍历数组
for ele in "${arr3[@]}"
do
# delete_topic $ele $host_ip
create_topic $ele $host_ip
done
exit 0
}
main "$@"