首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在bash脚本中使用文件描述符3中的" read“读取?

如何在bash脚本中使用文件描述符3中的" read“读取?
EN

Stack Overflow用户
提问于 2010-01-18 15:44:52
回答 3查看 23.3K关注 0票数 10

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

代码语言:javascript
复制
#!/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行的文件的名称。我还读了" read“的手册页,没有像”-u“这样的选项。

因此,如何从文件描述符3(即stdin的副本)中使用" read“进行读取。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-01-18 15:48:04

试一试

代码语言:javascript
复制
read key <&3
票数 15
EN

Stack Overflow用户

发布于 2015-02-03 14:04:15

也可以让bash将文件描述符分配给变量;下一个空闲描述符号将从10开始分配。

代码语言:javascript
复制
#!/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
票数 9
EN

Stack Overflow用户

发布于 2010-01-18 19:41:16

为了记录在案,这里还有另一个脚本:

代码语言:javascript
复制
# 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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2087188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档