2010-01-18 21 views
6

http://bash.cyberciti.biz/file-management/shell-script-to-simulate-unix-more-command/Làm thế nào để đọc bằng cách sử dụng "đọc" từ bộ mô tả tập tin 3 trong tập lệnh bash?

#!/bin/bash 
# Write a shell script like a more command. It asks the user name, the 
# name of the file on command prompt and displays only the 15 lines of 
# the file at a time. 
# ------------------------------------------------------------------------- 
# Copyright (c) 2007 nixCraft project <http://cyberciti.biz/fb/> 
# This script is licensed under GNU GPL version 2.0 or above 
# ------------------------------------------------------------------------- 
# This script is part of nixCraft shell script collection (NSSC) 
# Visit http://bash.cyberciti.biz/ for more information. 
# ------------------------------------------------------------------------- 

counter=1 
echo -n "Enter a file name : " 
read file 

if [ ! -f $file ] 
then 
    echo "$file not a file!" 
    exit 1 
fi 

# read file line by line 
exec 3<&0 
while read line 
do 
     # pause at line no. 15 
    if [ $counter -eq 15 ] 
    then 
     counter=0 # reset counter 
     echo " *** Press [Enter] key to continue ..." 
     read -u 3 enterKey 
    fi 
    echo $line 
    ((counter++)) 
done < $file 

này mô phỏng lệnh hơn .. tôi nhận được lỗi này ..

đọc: 26: Tùy chọn trái phép -u

Hãy chắc chắn để nhập vào tên của một tệp có hơn 15 dòng .. Ngoài ra tôi đọc trang người đàn ông "đã đọc" và tôi không nhận được tùy chọn như "-u" ..

Vì vậy, làm thế nào để tôi đọc bằng cách sử dụng "đọc" từ bộ mô tả tập tin 3 (là bản sao của stdin).

+0

Phiên bản Bash nào? –

Trả lời

11

thử

read key <&3 
+0

: omg: thật dễ dàng. thanx .. –

+0

Tôi nhận được: '-bash: 3: Trình mô tả tệp không hợp lệ' – Timo

0

Chỉ cần cho các hồ sơ, đây là thêm một kịch bản hơn:

# Author: Steve Stock 
# http://www.linuxjournal.com/article/7385 (comments) 

shmore() { 
LINES="" 
while read -d $'\n' line; do 
    printf "%s\n" "$line" 
    #echo "$line" 
    LINES=".${LINES}" 
    if [[ "$LINES" == "......................." ]]; then 
    echo -n "--More--" 
    read < /dev/tty 
    LINES="" 
    fi 
done 
return 0 
} 


shmore < file.txt 

tìm thấy ở đây: http://codesnippets.joyent.com/posts/show/1788

5

Cũng có thể để có được bash để gán một bộ mô tả tập tin để một biến số; Số mô tả miễn phí tiếp theo sẽ được phân bổ bắt đầu từ 10. Ví dụ:

#!/bin/bash 
FILENAME="my_file.txt" 
exec {FD}<${FILENAME}  # open file for read, assign descriptor 
echo "Opened ${FILENAME} for read using descriptor ${FD}" 
while read -u ${FD} LINE 
do 
    # do something with ${LINE} 
    echo ${LINE} 
done 
exec {FD}<&- # close file 
Các vấn đề liên quan