Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

ループのたびに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
aonisai
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away