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】readコマンドの使い方

Posted at

基本的な使い方

readコマンドを使用するとユーザーからの入力を受け取ることができます。
基本的な構文は以下の通りです。

read [オプション] [変数名...]

ユーザーからの入力を受け取り、その入力を変数に格納します。

read.sh
#!/bin/bash

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

このスクリプトを実行すると、ユーザーに名前の入力を促し、こんにちは、sampleさん!のように出力します。

ターミナル
$ bash read.sh
名前を入力してください:sample
こんにちは、sampleさん!

$ bash read.sh
名前を入力してください:test
こんにちは、testさん!

注意事項

Zshでread -p "名前を入力してください:" nameを実行すると以下のようなエラーが発生します。
Bashではなく、Zshで実行する場合にはread.shを以下のように書き換えます。

read.sh
#!/bin/zsh

read name"?名前を入力してください:"
echo "こんにちは、${name}さん!"
ターミナル
$ zsh read.sh
名前を入力してください:sample
こんにちは、sampleさん!

または、-pを使用せずechoでプロンプトを出力します。

read.sh
#!/bin/zsh

echo -n "名前を入力してください:"
read name
echo "こんにちは、${name}さん!"
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?