Lệnh read trong Linux dùng để nhận đầu vào từ người dùng qua dòng lệnh. Điều này hữu ích khi muốn tạo sự tương tác với người dùng tại thời điểm chạy (runtime).
Cú pháp lệnh read:
read [options] variable_name
Sau đó dùng ký hiệu $ trước tên biến để truy xuất giá trị, ví dụ: $variable_name.
Script Bash Đọc Đầu Vào Người Dùng
Tạo file với đuôi .sh, ví dụ:
touch user_input.sh
Mở file trong trình soạn thảo yêu thích và nhập:
#!/bin/bash
echo "Enter your name:"
read name
echo "Enter your age:"
read age
echo "Hello" $name, "you are" $age "years old"
Script trên đọc tên và tuổi của người dùng.
Lưu ý: Không cần khai báo kiểu dữ liệu cho biến đọc vào.
Để chạy script, mở terminal và gõ:
$ sh user_input.sh
Enter your name: DevQA
Enter your age: 12
Hello DevQA, you are 12 years old
Thông Báo Nhắc (Prompt) Với Lệnh Read
Để hiển thị thông báo nhắc cùng lệnh read, dùng tùy chọn -p.
Ví dụ:
$ read -p "Enter your username: " username
Nếu không muốn ký tự hiển thị trên màn hình (ví dụ nhập mật khẩu), dùng tùy chọn -s.
Ví dụ:
$ read -sp "Enter your password: " password
Script Bash đọc tên đăng nhập và mật khẩu:
#!/bin/bash
read -p "Enter your username: " username
read -sp "Enter your password: " password
echo -e "\nYour username is $username and Password is $password"
Kết quả:
$ sh user_input.sh
Enter your username: devqa
Enter your password:
Your username is devqa and Password is secret