2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

シェルスクリプトで規定時間処理を行う

Last updated at Posted at 2021-09-30

はじめに

「シェルを用いて数十秒、数分の間処理を行い続ける」
ということを行いたいということがある。
今回はそのサンプルとなるようなシェルスクリプトを紹介する。

シェルスクリプト

# !/bin/bash

# 開始時刻を取得
date_start=$(date +%Y/%m/%d-%H:%M:%S)
# 経過時間計算時使用するスタート時刻を取得
start_time=$(date "+%s")
# 経過時刻変数
elapsed_time=0

# 経過時間が10秒を経過したらwhile文を抜ける
while :; do
    if [ $elapsed_time -ge 10 ]; then
        echo "ここに行いたい処理を入れる"
        break
    else
        echo "処理中です"
        #1秒停止
        sleep 1
        #現在時間を算出
        current_time=$(date "+%s")
        #経過時間を計算
        elapsed_time=$(($current_time - $start_time))
    fi
done

# 終了時間を取得
date_end=$(date +%Y/%m/%d-%H:%M:%S)

echo "ループを抜けました。"
echo "$date_start に処理を開始"
echo "$date_end に処理を終了"

exit 0

使い方

if [ $elapsed_time -ge 10 ]; then

上記の「10」が処理を行う時間。
この数字を調整することで行う時間を調整する

echo "ここに行いたい処理を入れる"

上記部分に繰り返し行いたい処理を入れる

sleep 1

次に繰り返し処理をするまでのインターバルとして入れる

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?