如何读取标准输入时没有参数传递? [英] How to read stdin when no arguments are passed?

查看:217
本文介绍了如何读取标准输入时没有参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想的时候有没有参数(文件)使用标准输入脚本不起作用通过。有什么办法如何使用,而不是在这个code?

文件标准输入

我试过这样:

 如果[! -n $ 1]#检查是否存在参数
   然后
   $ 1 = $;如果没有使用标准输入作为一个参数(小于为/ dev /标准输入)#
   科幻VAR =$ 1
而读线
   做
   ...#找到最长行
   完成<$ VAR


解决方案

刚刚替补庆典的特殊间preTED 的/ dev /标准输入作为文件名:

  VAR = $ 1
而阅读等等;做
  ...
完成< $ {VAR: - 为/ dev /标准输入}

(请注意,庆典将实际使用特殊的文件的/ dev /标准输入如果专为它提供它的,但是因为bash的2.04将解决该文件的情况下对系统不支持它的操作系统。)

Script doesn't work when I want to use standard input when there are no arguments (files) passed. Is there any way how to use stdin instead of a file in this code?

I tried this:

if [ ! -n $1 ] # check if argument exists
   then
   $1=$(</dev/stdin)  # if not use stdin as an argument
   fi

var="$1"
while read line
   do
   ...                # find the longest line
   done <"$var"

解决方案

Just substitute bash's specially interpreted /dev/stdin as the filename:

VAR=$1
while read blah; do
  ...
done < "${VAR:-/dev/stdin}"

(Note that bash will actually use that special file /dev/stdin if built for an OS that offers it, but since bash 2.04 will work around that file's absence on systems that do not support it.)

这篇关于如何读取标准输入时没有参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆