LoginSignup
12

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

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
What you can do with signing up
12