Toán tử kiểm tra File trong Shell
Dưới đây là ví dụ sử dụng tất cả các toán tử kiểm tra File:
Giả sử một file biến giữ một tên file là "/var/www/tutorialspoint/unix/test.sh" mà có kích cỡ là 100 byte và cho phép đọc, ghi, và thực thi.
#!/bin/sh file="/var/www/tutorialspoint/unix/test.sh" if [ -r $file ] then echo "File has read access" else echo "File does not have read access" fi if [ -w $file ] then echo "File has write permission" else echo "File does not have write permission" fi if [ -x $file ] then echo "File has execute permission" else echo "File does not have execute permission" fi if [ -f $file ] then echo "File is an ordinary file" else echo "This is sepcial file" fi if [ -d $file ] then echo "File is a directory" else echo "This is not a directory" fi if [ -s $file ] then echo "File size is zero" else echo "File size is not zero" fi if [ -e $file ] then echo "File exists" else echo "File does not exist" fi
Nó sẽ cho kết quả sau:
File has read access File has write permission File has execute permission File is an ordinary file This is not a directory File size is zero File exists
Có một số điểm cần ghi nhớ:
Phải có các khoảng trống giữa các toán tử và các biểu thức, ví dụ: 2+2 là không đúng, nó nên được viết là 2 + 2.
Lệnh if…then…else…fi là một lệnh điều khiển luồng mà đã được giải thích trong chương tới.
Công cụ giáo viên (2048.VN)
Tạo- trộn đề thi miễn phí từ file PDF, Word, Giao bài nhanh chóng, Hoàn toàn Free
Các bài học UNIX phổ biến khác tại VietJack:
- Quản lý File
- Thư mục
- Quyền truy cập File
- Cài đặt Unix/Linux
- Các tiện ích cơ bản
- Các Pipe & Bộ lọc (Filter)
Dành cho bạn
Công cụ giáo viên
- Tạo đề online từ PDF / Word
- Trộn nhiều mã đề, in Offline
- Giao bài online, Quản lí lớp học

