คำสั่ง read ใน Linux ใช้สำหรับรับข้อมูลจากผู้ใช้ผ่านบรรทัดคำสั่ง (command line) นี่มีประโยชน์เมื่อเราต้องการให้ผู้ใช้โต้ตอบกับสคริปต์ขณะรัน (runtime)
ไวยากรณ์ของ read คือ:
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
ข้อความพร้อมท์ (Prompt) พร้อมคำสั่ง read
เพื่อแสดงข้อความพร้อมท์พร้อมกับคำสั่ง 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