Linux 実行遅延

LinuxLinuxBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Linux の sleep コマンドの使い方を学びます。このコマンドを使用すると、スクリプトやコマンドシーケンスに時間指定の一時停止や遅延を導入することができます。タイミングを制御する能力は、操作間の待機時間を作成したり、ユーザーの操作をシミュレートしたり、スクリプトの実行フローを制御したりするなど、多くのスクリプトタスクにおいて不可欠です。

この実験の終了時には、固定値と変数の両方を使用して sleep コマンドを使い、Linux シェルスクリプトで柔軟なタイミング制御を行う方法を理解するようになります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/BasicFileOperationsGroup(["Basic File Operations"]) linux(("Linux")) -.-> linux/BasicSystemCommandsGroup(["Basic System Commands"]) linux(("Linux")) -.-> linux/FileandDirectoryManagementGroup(["File and Directory Management"]) linux(("Linux")) -.-> linux/SystemInformationandMonitoringGroup(["System Information and Monitoring"]) linux(("Linux")) -.-> linux/VersionControlandTextEditorsGroup(["Version Control and Text Editors"]) linux/BasicSystemCommandsGroup -.-> linux/echo("Text Display") linux/BasicSystemCommandsGroup -.-> linux/bc("Arithmetic Calculations") linux/BasicSystemCommandsGroup -.-> linux/sleep("Execution Delaying") linux/BasicFileOperationsGroup -.-> linux/touch("File Creating/Updating") linux/BasicFileOperationsGroup -.-> linux/cut("Text Cutting") linux/BasicFileOperationsGroup -.-> linux/chmod("Permission Modifying") linux/FileandDirectoryManagementGroup -.-> linux/cd("Directory Changing") linux/SystemInformationandMonitoringGroup -.-> linux/date("Date/Time Displaying") linux/VersionControlandTextEditorsGroup -.-> linux/nano("Simple Text Editing") subgraph Lab Skills linux/echo -.-> lab-271383{{"Linux 実行遅延"}} linux/bc -.-> lab-271383{{"Linux 実行遅延"}} linux/sleep -.-> lab-271383{{"Linux 実行遅延"}} linux/touch -.-> lab-271383{{"Linux 実行遅延"}} linux/cut -.-> lab-271383{{"Linux 実行遅延"}} linux/chmod -.-> lab-271383{{"Linux 実行遅延"}} linux/cd -.-> lab-271383{{"Linux 実行遅延"}} linux/date -.-> lab-271383{{"Linux 実行遅延"}} linux/nano -.-> lab-271383{{"Linux 実行遅延"}} end

sleep コマンドの理解

Linux の sleep コマンドは、シンプルですが強力なユーティリティで、指定された時間だけスクリプトやコマンドシーケンスの実行を一時停止します。これは、コマンド間に遅延を作成する必要があるシェルスクリプトで特に有用です。

まずは、sleep コマンドの基本的な使い方を見ていきましょう。

まず、プロジェクトディレクトリに移動します。

cd ~/project

では、ターミナルで直接 sleep コマンドを使ってみましょう。次のコマンドを入力します。

echo "Start time: $(date +%H:%M:%S)"
sleep 3
echo "End time: $(date +%H:%M:%S)"

このコマンドシーケンスを実行すると、開始時間が表示され、その後 3 秒間の一時停止があり、そして終了時間が表示されます。出力は次のようになります。

Start time: 10:15:30
End time: 10:15:33

sleep コマンドの基本的な構文は次の通りです。

sleep NUMBER[SUFFIX]

ここで、

  • NUMBER は一時停止する時間です。
  • SUFFIX はオプションで、次のように指定できます。
    • s:秒 (サフィックスが指定されない場合のデフォルト)
    • m:分
    • h:時間
    • d:日

異なる時間単位がどのように機能するかを見るために、いくつかの例を試してみましょう。

## Sleep for 5 seconds
echo "Sleeping for 5 seconds..."
sleep 5
echo "Done!"

## Sleep for 0.5 seconds (half a second)
echo "Sleeping for half a second..."
sleep 0.5
echo "Done!"

これで、sleep コマンドの基本的な動作が理解できました。次のステップでは、これをシェルスクリプトに組み込みます。

sleep を使用した基本的なシェルスクリプトの作成

これで sleep コマンドの動作が理解できたので、これを使用したシェルスクリプトを作成しましょう。シェルスクリプトを使用すると、コマンドのシーケンスを自動化でき、Linux 管理における基本的なツールです。

まず、プロジェクトディレクトリに新しいシェルスクリプトファイルを作成しましょう。

cd ~/project
touch delay_script.sh

次に、nano テキストエディタを使用してファイルを開きます。

nano delay_script.sh

ファイルに次の内容を追加します。

#!/bin/zsh

echo "Starting the script..."
echo "First message appears immediately."
sleep 2
echo "Second message appears after 2 seconds."
sleep 3
echo "Third message appears after 3 more seconds."
echo "Script execution complete."

nano でファイルを保存するには、Ctrl+O を押し、Enter を押して確認し、最後に Ctrl+X を押してエディタを終了します。

スクリプトを実行する前に、実行可能にする必要があります。

chmod +x delay_script.sh

では、スクリプトを実行しましょう。

./delay_script.sh

指定された遅延でメッセージが表示されるはずです。

Starting the script...
First message appears immediately.
Second message appears after 2 seconds.
Third message appears after 3 more seconds.
Script execution complete.

このシンプルなスクリプトは、sleep コマンドを使用してメッセージ表示のタイミングを制御できることを示しています。この手法は、多くのスクリプトシナリオで役立ちます。例えば、

  1. ユーザー操作のシミュレーション
  2. プロセスの完了を待つ
  3. 進捗インジケーターの作成
  4. 操作のレート制限

スクリプトが一行ずつ何をするかを見てみましょう。

  1. #!/bin/zsh - これはシバン行と呼ばれ、スクリプトを zsh シェルで実行することを指定します。
  2. echo "Starting the script..." - 初期メッセージを表示します。
  3. echo "First message appears immediately." - 最初のメッセージをすぐに表示します。
  4. sleep 2 - スクリプトの実行を 2 秒間一時停止します。
  5. echo "Second message appears after 2 seconds." - 2 秒間の遅延後に 2 番目のメッセージを表示します。
  6. sleep 3 - スクリプトの実行をさらに 3 秒間一時停止します。
  7. echo "Third message appears after 3 more seconds." - 3 秒間の遅延後に 3 番目のメッセージを表示します。
  8. echo "Script execution complete." - 最終メッセージを表示します。

次のステップでは、変数を使用して sleep の持続時間をより柔軟にする方法を探ります。

sleep コマンドでの変数の使用

実際のスクリプトでは、ハードコードされた sleep 時間よりも柔軟性が必要なことがよくあります。sleep 時間に変数を使用することで、スクリプトをより適応性が高く、保守しやすくすることができます。この概念を示す新しいスクリプトを作成しましょう。

まず、新しいファイルを作成します。

cd ~/project
touch variable_delay.sh

nano でファイルを開きます。

nano variable_delay.sh

次の内容を追加します。

#!/bin/zsh

## Define delay durations as variables
SHORT_DELAY=1
MEDIUM_DELAY=3
LONG_DELAY=5

echo "Starting the script with variable delays..."

echo "This is displayed immediately."
echo "Waiting for a short delay (${SHORT_DELAY} seconds)..."
sleep $SHORT_DELAY
echo "Short delay completed."

echo "Waiting for a medium delay (${MEDIUM_DELAY} seconds)..."
sleep $MEDIUM_DELAY
echo "Medium delay completed."

echo "Waiting for a long delay (${LONG_DELAY} seconds)..."
sleep $LONG_DELAY
echo "Long delay completed."

echo "Script execution complete."

Ctrl+OEnterCtrl+X を使用して nano を保存して終了します。

スクリプトを実行可能にします。

chmod +x variable_delay.sh

では、スクリプトを実行しましょう。

./variable_delay.sh

出力は次のようになります。

Starting the script with variable delays...
This is displayed immediately.
Waiting for a short delay (1 seconds)...
Short delay completed.
Waiting for a medium delay (3 seconds)...
Medium delay completed.
Waiting for a long delay (5 seconds)...
Long delay completed.
Script execution complete.

遅延時間に変数を使用することが有益な理由を理解しましょう。

  1. 可読性SHORT_DELAY のような説明的な変数名を使用すると、コードが自己文書化されます。
  2. 保守性:遅延時間を変更する必要がある場合、スクリプト全体ではなく、変数宣言の 1 箇所だけを変更する必要があります。
  3. 一貫性:同じ遅延時間が複数回使用される場合、変数を使用するとすべてのインスタンスで同じ値が使用されることが保証されます。
  4. 柔軟性:変数の値を変更するだけで、遅延時間を簡単に変更できます。

これらの変数を使って計算を行うこともできます。それを示すために、もう 1 つのスクリプトを作成しましょう。

cd ~/project
touch calculated_delay.sh
nano calculated_delay.sh

次の内容を追加します。

#!/bin/zsh

## Base delay time in seconds
BASE_DELAY=2

echo "Starting script with calculated delays..."

## Using the base delay
echo "Waiting for the base delay (${BASE_DELAY} seconds)..."
sleep $BASE_DELAY
echo "Base delay completed."

## Double the base delay
DOUBLE_DELAY=$((BASE_DELAY * 2))
echo "Waiting for double the base delay (${DOUBLE_DELAY} seconds)..."
sleep $DOUBLE_DELAY
echo "Double delay completed."

## Half the base delay
HALF_DELAY=$(echo "scale=1; $BASE_DELAY / 2" | bc)
echo "Waiting for half the base delay (${HALF_DELAY} seconds)..."
sleep $HALF_DELAY
echo "Half delay completed."

echo "Script execution complete."

保存して nano を終了し、スクリプトを実行可能にします。

chmod +x calculated_delay.sh

スクリプトを実行します。

./calculated_delay.sh

出力は次のようになります。

Starting script with calculated delays...
Waiting for the base delay (2 seconds)...
Base delay completed.
Waiting for double the base delay (4 seconds)...
Double delay completed.
Waiting for half the base delay (1.0 seconds)...
Half delay completed.
Script execution complete.

これは、単一の基本値に基づいて遅延時間を動的に計算できることを示しており、スクリプトをさらに柔軟で強力にします。

sleep コマンドの実用的なアプリケーション

これで sleep コマンドの基本と変数を使った使い方が理解できたので、いくつかの実用的なアプリケーションを探ってみましょう。これらの例は、sleep コマンドが実際のシナリオでどのように使用されるかを示しています。

シンプルなカウントダウンタイマーの作成

sleep コマンドのより複雑な使い方を示すカウントダウンタイマーを作成しましょう。

cd ~/project
touch countdown.sh
nano countdown.sh

次の内容を追加します。

#!/bin/zsh

## Function to display a countdown
countdown() {
  local seconds=$1
  while [ $seconds -gt 0 ]; do
    echo -ne "\rTime remaining: $seconds seconds "
    sleep 1
    ((seconds--))
  done
  echo -e "\rCountdown complete!            "
}

## Specify the countdown duration
echo "Starting a 5-second countdown:"
countdown 5
echo "Countdown script execution complete."

保存して nano を終了し、スクリプトを実行可能にします。

chmod +x countdown.sh

スクリプトを実行します。

./countdown.sh

5 秒から 0 までのカウントダウンが表示され、時間がその場で更新されるはずです。

Starting a 5-second countdown:
Time remaining: 5 seconds
Time remaining: 4 seconds
Time remaining: 3 seconds
Time remaining: 2 seconds
Time remaining: 1 seconds
Countdown complete!
Countdown script execution complete.

進捗インジケーター付きのプロセスのシミュレーション

シンプルな進捗インジケーター付きの長時間実行されるプロセスをシミュレートするスクリプトを作成しましょう。

cd ~/project
touch progress.sh
nano progress.sh

次の内容を追加します。

#!/bin/zsh

## Function to show a simple progress bar
show_progress() {
  local duration=$1
  local steps=10
  local step_duration=$(echo "scale=2; $duration / $steps" | bc)

  echo "Starting process..."
  echo -n "Progress: ["
  for i in {1..10}; do
    sleep $step_duration
    echo -n "#"
  done
  echo "] Done!"
}

## Run a process that takes 5 seconds with a progress indicator
show_progress 5
echo "Process completed successfully."

保存して nano を終了し、スクリプトを実行可能にします。

chmod +x progress.sh

スクリプトを実行します。

./progress.sh

5 秒間で埋まる進捗バーが表示されるはずです。

Starting process...
Progress: [##########] Done!
Process completed successfully.

操作のレート制御

この例では、sleep コマンドを使用して操作のレートを制御する方法を示します。これは、API 呼び出しのレート制限や大規模なデータセットの処理に役立ちます。

cd ~/project
touch rate_limit.sh
nano rate_limit.sh

次の内容を追加します。

#!/bin/zsh

## Define the rate limit (operations per second)
OPERATIONS_PER_SECOND=2
SLEEP_DURATION=$(echo "scale=3; 1 / $OPERATIONS_PER_SECOND" | bc)

echo "Performing operations at a rate of $OPERATIONS_PER_SECOND per second"
echo "Each operation will be followed by a $SLEEP_DURATION second delay"

## Simulate 6 operations with rate limiting
for i in {1..6}; do
  echo "Performing operation $i at $(date +%H:%M:%S.%N | cut -c1-12)"
  ## Simulate the operation
  sleep 0.1
  ## Rate-limiting delay between operations
  if [ $i -lt 6 ]; then
    sleep $SLEEP_DURATION
  fi
done

echo "All operations completed"

保存して nano を終了し、スクリプトを実行可能にします。

chmod +x rate_limit.sh

スクリプトを実行します。

./rate_limit.sh

操作が制御されたレートで実行されるのが見えるはずです。

Performing operations at a rate of 2 per second
Each operation will be followed by a 0.500 second delay
Performing operation 1 at 10:30:45.12
Performing operation 2 at 10:30:45.72
Performing operation 3 at 10:30:46.32
Performing operation 4 at 10:30:46.92
Performing operation 5 at 10:30:47.52
Performing operation 6 at 10:30:48.12
All operations completed

これらの例は、sleep コマンドがより高度なスクリプトシナリオでどのように使用できるかを示しています。タイミングを制御する能力は、多くの実用的なアプリケーションを可能にするシェルスクリプトの強力なツールです。

まとめ

この実験では、Linux で sleep コマンドを使用してシェルスクリプトにタイム遅延を導入する方法を学びました。これは、制御されたタイミングを必要とするスクリプトの作成やコマンドライン操作における基本的なスキルです。

この実験でカバーされた主要な概念は以下の通りです。

  1. 異なる時間単位(秒、分、時間)での sleep コマンドの基本的な使い方
  2. sleep コマンドを組み込んだシェルスクリプトの作成
  3. 睡眠時間をより柔軟で保守しやすくするための変数の使用
  4. 睡眠時間の変数を使った計算の実行
  5. sleep コマンドの実用的なアプリケーション:
    • カウントダウンタイマーの作成
    • 進捗インジケーターの実装
    • 操作のレート制御

これらのスキルは、以下を含む多くの Linux スクリプトシナリオで役立ちます。

  • 特定のタイミングを必要とするタスクの自動化
  • 適切な一時停止を伴う使いやすいインターフェースの作成
  • API 呼び出しやリソースを大量に消費する操作のレート制限の実装
  • ユーザーインタラクションのシミュレーション
  • スクリプト実行のフローの管理

sleep コマンドを習得することで、より洗練された使いやすいスクリプトを作成するのに役立つ重要なツールが Linux スクリプトツールキットに加わりました。