6
10

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.

【sh】for文を使って配列の中の変数を読む

Last updated at Posted at 2018-03-01

番号順に並んだ変数を順番に読む方法を "【シェルスクリプト】 for文を使って名前に数字が入っている変数を読み込む" でまとめましたが、配列を使う方法を思いついたのでまとめます。

やり方

次のように変数に値が入っています。

var1=1
var2=6
var3=13
var4=18
var5=24
var6=26

これを配列に代入します。

array=($var1 $var2 $var3 $var4 $var5 $var6)

arrayをfor文で順番に取り出します。

for var in ${array[@]}
do
    var=`printf %02d ${var}`
    echo $var
done

結果

01
08
13
18
24
26

  
こちらのやり方のほうが変数を追加したときにも対応しやすいのでいいと思いました。

6
10
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
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?