0
0

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 3 years have passed since last update.

シェルスクリプトで呼び出し元の配列変数を読み取る

Posted at

はじめに

変数にセットした配列の値をシェルスクリプトから読み取ろうとした所、上手くいかなかったので自分なりの解決方法をメモします。

上手くいかなかった例

まず、以下の様なシェルスクリプトを想定します。


# ! /bin/bash

ARRAY=(1 2 3)
echo "${ARRAY[@]}"

このスクリプトを実行すると以下の様になります。


$ ./test.sh
1 2 3

では、スクリプトを以下の様に修正し、ARRAYを呼び出し元から読み取るようにします。が、bashでは配列のエクスポートがサポートされていないようで、期待する結果にはなりませんでした。(参考: https://www.mazn.net/blog/2008/11/29/161.html)


# ! /bin/bash

echo "${ARRAY[@]}"
$ export ARRAY=(1 2 3)
$ ./test.sh

解決方法

一旦配列の中身を環境変数として設定し、スクリプト内部で配列として再定義することで期待する結果を得ることができました。


# ! /bin/bash

ARRAY=($ARRAY)
echo "${ARRAY[@]}"
$ export ARRAY="1 2 3"
$ ./test.sh
1 2 3

最後に

今回は、変数にセットされた配列の値をスクリプトから読み取る方法を書きました(厳密には配列は読み取っていないですが)。シェルスクリプトは初心者なのでこれが正しい方法なのかはわかりません。もっと良い方法があれば教えていただきたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?