2010-01-18 68 views
6

http://bash.cyberciti.biz/file-management/shell-script-to-simulate-unix-more-command/如何在bash腳本中使用文件描述符3中的「讀取」來讀取?

#!/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 

這模擬多個命令.. 我得到這個錯誤..

讀:26:-u

非法選項確保輸入的名稱一個文件有超過15行.. 此外我讀了「閱讀」的手冊頁,我沒有得到像「-u」的選項..

那麼,我如何閱讀使用「讀取」從文件描述符3(這是stdin的副本)。

+0

什麼的Bash版本: 接下來的空閒描述符數量將從10 例如開始進行分配? – 2010-01-18 16:18:40

回答

11

嘗試

read key <&3 
+0

:omg:那很容易。 thanx .. – 2010-01-18 15:51:53

+0

我得到:'-bash:3:Bad file descriptor' – Timo 2018-03-02 06:58:30

0

只是爲了記錄在案,這裏的又一多個腳本:

# 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 

這裏找到:http://codesnippets.joyent.com/posts/show/1788

5

也有可能得到的bash的文件描述符分配給一個變量;

#!/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 
相關問題