22
17

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.

シェルスクリプトで変数のインクリメント

Posted at

ループのたびに1加算する方法のメモ
いくつも書き方があって面白い

exprを使う例
一番一般的なのかな?

sample1.sh
#!/bin/bash
count=0
while true
do
  echo $count
  count=`expr $count + 1`
  if [ $count -eq 10 ]; then
    exit 0
  fi
done

bcを使う例
個人的にはexprよりbcのほうが複雑なことができるので好き

sample2.sh
#!/bin/bash
count=0
while true
do
  echo $count
  count=`echo "$count+1" | bc`
  if [ $count -eq 10 ]; then
    exit 0
  fi
done

括弧()を使う例
shでは使えないらしいです(未検証)。

sample3.sh
#!/bin/bash
count=0
while true
do
  echo $count
  count=$((count++))
  if [ $count -eq 10 ]; then
    exit 0
  fi
done

[]を使う例
こちらもshでは使えないらしいです。未検証

sample4.sh
#!/bin/bash
count=0
while true
do
  echo $[count++]
  if [ $count -eq 10 ]; then
    exit 0
  fi
done

実行結果

$ ./sample1.sh
0
1
2
3
4
5
6
7
8
9
22
17
1

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
22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?