1
1

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 5 years have passed since last update.

シェルスクリプト while 文

Posted at

以下の算術式の 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
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?