1
1

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.

シェルスクリプトで配列の格納ができなかった話

Last updated at Posted at 2021-01-23

とあるデータをシェルスクリプトで読み取ろうとして失敗したお話

test.txt
aaaaaa
iiiiii
read.sh
TEXTFILE=./test.txt

echo "start"

cat ${TEXTFILE} | while read line
do
 echo ${line}
done

echo "done"
$ sh read.sh
start
aaaaaa
iiiiii
done

これで問題なく動作する

これを配列に格納するようにする場合

read.sh
TEXTFILE=./test.txt
declare -a list

echo "start"

cat ${TEXTFILE} | while read line
do
 list+=(${line})
done

echo ${list}
echo "done"
$ sh read.sh
start

done

実行結果としては配列に入っていて欲しいデータがない状態となる

この原因としては下記のようにパイプ用いる場合、パイプ以降の処理が別のプロセスとして処理される
cat ${TEXTFILE} | while read line

今回で言うとwhileは別の処理として扱われてしまうためlistにデータが格納されない

改善方法

早い話がパイプを使わなければいい

read.sh
TEXTFILE=./test.txt
declare -a list

echo "start"
DATA=`cat ${TEXTFILE}`

while read line
do
  list+=(${line})
done << FILE
${DATA}
FILE

echo ${list[*]}
echo "done"
$ sh read.sh
start
aaaaaa iiiiii
done

改行は配列の出力の仕方を変えればいいので今回は省略

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?