[Bash] read で標準入力から1行を変数に読み込む
作成日: 2026年10月02日
Bash の read を使用すると、標準入力から1行を読み込んで変数に格納できます。
read -r line <<< 'hello world'
printf '%s\n' "$line"
実行結果は下記のとおりです。
hello world
line は読み込んだ文字列を格納する変数名です。
-r オプションを付けると、バックスラッシュをエスケープ文字として扱わず、そのまま読み込みます。任意の文字列を読み込む場合は -r を付けておくと安全です。
<<< はヒアストリングで、右側の文字列をコマンドの標準入力として渡します。
参考
- Bash Reference Manual - Bash Builtin Commands: https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html