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.

複数行の文字列をShell変数に格納して、forで回した時の挙動

Posted at

double quoteで囲むと改行して出力する

double quoteで囲むと改行して出力する。

囲まないと半角スペースになる。

LINES=`cat <<EOF
line1
line2
line3
EOF
`

echo ${LINES}
echo "${LINES}"

output

line1 line2 line3
line1
line2
line3

for文で回すときはdouble quoteで囲まない

for文で回してもらうときは半角区切りで渡す必要があるため、double quoteで囲まないほうがいい。

double quoteで区切ると1行の文字列として扱われてしまう。

#!/bin/bash
# your code goes here

LINES=`cat <<EOF
line1
line2
line3
EOF
`

COUNT=0
for i in ${LINES}
do
  echo ${COUNT}':'${i}
  COUNT=$(( COUNT + 1 ))
done

COUNT=0
for i in "${LINES}"
do
  echo ${COUNT}':'${i}
  COUNT=$(( COUNT + 1 ))
done

output

0:line1
1:line2
2:line3
0:line1 line2 line3

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?