【脚本】 【Linux】循环执行命令

loop.sh

#!/bin/bash

if [ "" = "$1" ]; then
    echo '用法: ./loop.sh 命令内容 时间间隔(毫秒) 循环次数(小于0表示无限循环)'
    echo '示例: ./loop.sh "ps -ef" 1000 10'
    exit 0
fi

interval=1000
if [ "" != "$2" ]; then
    if echo "$2" | grep -q "^[0-9]*$"; then
        interval=$2
    else
        echo "第2个参数必须为数字"
        exit 0
    fi
fi
interval=$(echo "scale=3; $interval/1000" | bc)

count=0
if [ "" != "$3" ]; then
    if echo "$3" | grep -q "^[0-9]*$"; then
        count=$3
    else
        echo "第3个参数必须为数字"
        exit 0
    fi
fi

echo "[`date +"%Y-%m-%d %H:%M:%S"`] 开始"
echo

if [ $count -gt 0 ]; then
    for((i=1;i<=$count;i++)); do
        echo "[`date +"%Y-%m-%d %H:%M:%S"`] 执行第[$i]次"
        bash -c "$1"
        if [ $i -lt $count ]; then
            sleep $interval
        fi
    done
else
    i=1
    while true
    do
        echo "[`date +"%Y-%m-%d %H:%M:%S"`] 执行第[$i]次"
        bash -c "$1"
        sleep $interval
        i=$(expr $i + 1)
    done
fi

echo
echo "[`date +"%Y-%m-%d %H:%M:%S"`] 结束"

用法: ./loop.sh 命令内容 时间间隔(毫秒) 循环次数(小于0表示无限循环),当命令内容存在空格时,需要用双引号包含。
示例:

./loop.sh ls 1000 10
./loop.sh "ps -ef"

猜你喜欢

转载自blog.csdn.net/hezhanran/article/details/133135375