以下の算術式の for 文は bash でしか動かないため、while 文を使用したほうがよい。
シェルスクリプト bash for 文 算術式
if 文と同様に、test コマンドの [ が記述されることが多い
インクリメントには expr コマンドを使用。
while-1.sh
i=1
while [ "$i" -le 10 ]; do
echo "$i"
i=`expr "$i" + 1`
done
bash の場合、インクリメントに算術式の使用が可能。
while-2.sh
i=1
while [ "$i" -le 10 ]; do
echo "$i"
((i++))
done
引数を順次処理する
shift コマンドで引数をずらす。
while-3.sh
while [ "$#" -gt 0 ]; do
echo "$1"
shift
done
while-3.sh_result
$ ./while-3.sh a b c
a
b
c
無限ループ
: コマンドを while の条件として記述(常に真を返す)
true コマンドを使用することも可能だが、true コマンドが外部コマンドとして実装されている場合もあるため、内部コマンドである : を使用したほうが良い。
while-4.sh
while : ;do
echo "yes"
done
bash ではどちらも内部コマンドなので問題ないはず。
$ type :
: is a shell builtin
$ type true
true is a shell builtin