Linux の読み取り command は、コマンド ラインからユーザー入力を取得するために使用されます。これは、実行時にユーザーの対話性を提供したい場合に便利です。
読み取り構文は次のとおりです:
read [options] variable_name
次に $
を使用できます 変数名の前に記号を付けて、その値にアクセスします。 $variable_name
.
ユーザー入力を読み取る Bash スクリプト
.sh
でファイルを作成することから始めます 拡張子、例:
touch user_input.sh
次に、お気に入りのエディターでファイルを開き、次のように入力します。
#!/bin/bash
echo "Enter your name:"
read name
echo "Enter your age:"
read age
echo "Hello" $name, "you are" $age "years old"
上記のスクリプトは、ユーザーの名前と年齢を受け取ります。
注:読み取る変数の型を指定する必要はありません。上記のスクリプトを実行するには、ターミナルを開いて次のように入力します。
$ sh user_input.sh
Enter your name:
DevQA
Enter your age:
12
Hello DevQA, you are 12 years old
読み取りコマンドによるプロンプト メッセージ
read コマンドでメッセージを表示するには、-p
を使用します オプション。
例:
$ read -p "Enter your username: " username
文字を画面に表示したくない場合は、 -s
を使用する必要があります read コマンドのオプション。これは、パスワードを読み取るときに役立ちます。
例:
$ read -sp "Enter your password: " password
上記のユーザー入力を読み取る bash スクリプトは次のようになります:
#!/bin/bash
read -p "Enter your username: " username
read -sp "Enter your password: " password
echo -e "\nYour username is $username and Password is $password"
出力は次のとおりです:
$ sh user_input.sh
Enter your username: devqa
Enter your password:
Your username is devqa and Password is secret