LoginSignup
8

シェルの文字列変数に改行を書き入れる方法

Last updated at Posted at 2019-10-16

こんにちは。
シェルの文字列変数へ改行\nを書き入れる方法を調べました。

Bash の場合

Bash の場合には、下記の方法を用いて、\n を直接書き入れられます。

$ LF=$'\n'
$ echo "$LF"
POSIX の場合

POSIX の場合には、\n を直接シンプルに書き入れる方法は無いようです。したがって、下記方法のように工夫する必要があります。printf で出力を確認しました。

$ ./hello.sh 
hello
world
hello.sh
#!/bin/sh
LF="
"
LF=$(printf '\n_');LF=${LF%_} # こちらでもOK(また '\012_' と書いてもよい)
#   LF=$(printf '\n') # これはダメ(なぜならば末尾の \n は全て除去されるので)

helloworld="hello${LF}world" # 変数 helloworld の作り方は下記でもOK
helloworld=$(cat << EOS
hello
world
EOS
)
#   helloworld="hello\nworld" # これはダメ(このように直接シンプルに \n を書き入れることはできない)

printf "%s\n" "$helloworld"

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
What you can do with signing up
8