若想要讀取 Bash 用戶輸入,您需要使用內(nèi)置的 Bash 命令read
。語法:
read <variable_name>
1.使用read
命令從 Bash 腳本中分別讀取單個(gè)和多個(gè)變量。
#!/bin/bash
echo "Enter the your name: "
read user_name
echo "Your name is $user_name"
echo
echo "Enter your age, phone and email: "
read age phone email
echo "your age is:$age, phone is:$phone, email: $email "
2.使用-p PROMPT
命令行選項(xiàng)在同一行上輸入。
#!/bin/bash
read -p "username:" user_var
echo "The username is: " $user_var
3.在靜默模式下,使用命令行選項(xiàng)-s
,-p
來傳遞用戶名并隱藏密碼
注:
-s
指用戶將輸入保持在靜默模式,-p
指用戶在新的命令提示符下輸入。
#!/bin/bash
read -p "username : " user_var
read -sp "password : " pass_var
echo
echo "username : " $user_var
echo "password : " $pass_var
4.使用-a
命令行選項(xiàng)對(duì)數(shù)組進(jìn)行多個(gè)輸入。
注:
-a
指腳本讀取數(shù)組,而variable_name
是引用數(shù)組變量名稱。
#!/bin/bash
echo "Enter names : "
read -a names
echo "The entered names are : ${names[0]}, ${names[1]}."
更多建議: