今回は、シェルスクリプトのでwhileの使い方を説明します。

手順

  1. CentOS81号機にログイン
  2. シェルスクリプト作成
  3. 動作確認

1.CentOS81号機にログイン

TeraTermで、CentOS1号機にrootでログインします。

2.シェルスクリプト作成

# シェルスクリプトの作成
[root@CE08PRDD104 tmp]# vi while.sh
!/bin/bash

while animal in dog cat bird
do
echo $animal
done

# シェルスクリプトに実行権を付与する
[root@CE08PRDD104 tmp]# chmod +x while.sh

# シェルスクリプトの実行
[root@CE08PRDD104 tmp]# . while.sh
dog
cat
bird

# ■■■ 1.事前準備
# 作業ディレクトリ作成
[root@CE08PRD101 ~]# mkdir -p /work/while;cd /work/while;pwd
/work/while

# テストファイル作成
[root@CE08PRD101 while]# vim test_while.sh
#!/bin/bash

count=0
while [ $count -lt 10 ]
do
echo $count
count=$(($count + 1))
done

# ファイル実行
[root@CE08PRD101 while]# bash test_while.sh
0
1
2
3
4
5
6
7
8
9

# テストファイル作成
[root@CE08PRD101 while]# vim test_while_2.sh
#!/bin/bash

read animal
while [ "$animal" = "dog" ]
do
echo "NG"
read animal
done
echo "OK"

# ファイル実行
[root@CE08PRD101 while]# bash test_while_2.sh
「cat」と入力する
NG
「dog」と入力する
OK

# 作業ディレクトリ削除
[root@CE08PRD101 zgip]# cd ../;rm -fr while