如何在Bash脚本中使用“read”从文件描述符3中读取?

12

http://bash.cyberciti.biz/file-management/shell-script-to-simulate-unix-more-command/

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

这里模拟了more命令,但是我收到了这个错误:

read: 26: Illegal option -u

请确保输入的文件名有超过15行.. 另外我阅读了“read”命令的man页面,但我没有找到像"-u"这样的选项。

那么,如何使用“read”从文件描述符3(即stdin的副本)中读取呢?


read -u 已经是 Bash 的一部分很长很长时间了。你也许确实在使用 sh 运行脚本吗?另请参阅 sh 和 bash 之间的区别 - tripleee
3个回答

17

尝试

read key <&3

3
我得到了:-bash: 3: 坏的文件描述符 - Timo
@Timo - 也许在尝试读取之前,你需要打开文件描述符号3?例如使用 exec 3< /path/to/file - mpb

10

还可以让bash将文件描述符分配给一个变量; 下一个可用的描述符编号将从10开始分配。 例如:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接