Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

番号順に並んだ変数を順番に読む方法を "【シェルスクリプト】 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

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

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした