且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何读取标准输入时没有参数传递?

更新时间:2023-11-17 23:52:58

刚刚替补庆典的特殊间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.)