shell 并发执行模板

运维过程中常常遇到大批量的重复运行某些脚本,单线程执行速度往往很慢,这里提供一个并发执行的 shell 脚本,有详细的日志打印和结果输出:

  • LOG_FILE:存储命令执行日志文件,包括异常日志
  • RES_FILE:存储输出结果
  • INPUT_FILE:批量输入的内容,如:一组文件列表
#!/bin/bash

##################################
#
# shell 并发脚本模板
#
##################################

start_time=$(date +%s)
current_datemin=$(date +"%Y%m%d%H%M")

# 当前脚本文件名(不包含父目录路径)
filename=$(basename "$0")
# 输入文本
INPUT_FILE="demo.txt"
# 并发线程数(使用当前机器线程)
CONCURRENCY=1
# 日志输出文件
LOG_FILE="${filename}_${current_datemin}.log"
# 结果输出文件
RES_FILE="${filename}_${current_datemin}.res"

# 示例,xargs 会重开一个 shell,因此无法获取当前 shell 中的变量,需要以传参的方式传入
hello="hello"
# 示例数据
echo "tom" > demo.txt
echo "jerry" >> demo.txt

# 清理旧的输出文件
if [ -f "$LOG_FILE" ]; then
    rm "$LOG_FILE"
fi

# 清理旧的输出文件
if [ -f "$RES_FILE" ]; then
    rm "$RES_FILE"
fi

cat $INPUT_FILE | awk '{print $NF}' | xargs -P $CONCURRENCY -I {} bash -c '
    # 示例:需要并发执行的命令,替换成自己的命令即可
    hello=$1
    echo "hello ${world}" >> "$RES_FILE"

' _ {} "$hello" >> "$LOG_FILE" 2>&1

end_time=$(date +%s)
execution_time=$((end_time - start_time))

echo "执行结束,执行时间: ${execution_time} 秒" >> "$LOG_FILE"

cat $LOG_FILE
posted @ 2025-11-28 15:34  tonyabasy  阅读(0)  评论(0)    收藏  举报