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?

[Linux][command] 制御_read

Last updated at Posted at 2025-06-06

readコマンド

$ read [オプション] 変数名
オプション 由来 説明
default read variable 標準入力から1行読み込み、変数に代入

使用例

1. 標準入力からの読み取り

ユーザーからキーボードでの入力を受け取る方法です。

/greeting.sh
#!/bin/bash

echo -n "名前を入力してください: "
read name
echo "こんにちは、$name さん!"

実行例:

$ ./greeting.sh
名前を入力してください: 太郎
こんにちは、太郎 さん!

2. リダイレクトを使ったファイルからの読み取り

ファイルの内容を1行ずつ読み取るには、while read ループと < ファイル名 を使います。

/read_file.sh
#!/bin/bash

while read line
do
  echo "読み取り内容: $line"
done < sample.txt

実行例 (sample.txt の内容):

sample.txt
りんご
バナナ
ぶどう

実行結果:

$ ./read_file.sh
読み取り内容: りんご
読み取り内容: バナナ
読み取り内容: ぶどう

3.パイプからの読み取り

read_pipe.sh
#!/bin/bash

cat sample.txt | while read line
do
  echo "パイプ読み取り: $line"
done

実行例(sample.txt の内容):

sample.txt
東京
大阪
名古屋

実行結果:

$ ./read_pipe.sh
パイプ読み取り: 東京
パイプ読み取り: 大阪
パイプ読み取り: 名古屋

Ping-t

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?