LoginSignup
0
0

シェルスクリプトでループを回したとき配列の1番目の要素しか取得できなかった

Last updated at Posted at 2023-07-12

環境

vscode
拡張機能BASH Extension Pack
今回扱うのはBASH Extension Pack内のshellcheck

次のようなbashファイルを書いていたとき次のようなメッセージが表示された。

loop.bash
#!/bin/bash

num=(12 14 18 44 53 80 87 114)

for i in $num; do
    echo ${i}
done

shell checkによるエラーメッセージ
Expanding an array without an index only gives the first element.shellcheckSC2128

どうやら配列の一つ目の要素しかループで取り出せないらしい。

実行結果

$ ./loop.bash
12

以下のように書き換えるとすべての要素が取得できた。

loop.bash
#!/bin/bash

num=(12 14 18 44 53 80 87 114)

for i in "${num[@]}"; do
    echo ${i}
done

変更部分はループの

$num->"${num[@]}"

です。

実行結果

$ ./loop.bash
12
14
18
44
53
80
87
114

参考
https://www.shellcheck.net/wiki/SC2128

0
0
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
0
0