Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 读取文件或读取标准用户输入_Bash - Fatal编程技术网

Bash 读取文件或读取标准用户输入

Bash 读取文件或读取标准用户输入,bash,Bash,我在编写bash脚本时遇到了一个问题。我被要求写一个脚本,可以通过两种方式调用,读取文件或读取标准输入。然而,当我使用了一段时间阅读时,我不能再让它阅读标准输入。这是我的密码: #!/bin/bash FILE=$1 while read LINE; do echo "$LINE" | tr " " "\n" | tr "\t" "\n" done < $FILE #/bin/bash 文件=$1 读行时; 做 回显“$LINE”| tr“\n”| tr“\t”\n 完成

我在编写bash脚本时遇到了一个问题。我被要求写一个脚本,可以通过两种方式调用,读取文件或读取标准输入。然而,当我使用了一段时间阅读时,我不能再让它阅读标准输入。这是我的密码:

#!/bin/bash
FILE=$1
while read LINE; 
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done < $FILE
#/bin/bash
文件=$1
读行时;
做
回显“$LINE”| tr“\n”| tr“\t”\n
完成<$FILE

问题来自这样一个事实:您总是将$FILE作为输入提供给read。 如果有参数,可以尝试将文件重定向到通道0,否则将其留给stdin

#!/bin/bash
FILE=$1
if [ ! -z "$FILE" ]
then
  exec 0< "$FILE"
fi
while read LINE
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done
#/bin/bash
文件=$1
如果[!-z“$FILE”]
然后
执行0<“$FILE”
fi
读行时
做
回显“$LINE”| tr“\n”| tr“\t”\n
完成
exec 0<“$FILE”
告诉shell使用$FILE作为通道0的输入。提醒:默认情况下,
read
收听频道0


按照惯例,UNIX工具使用特殊文件名
-
来指示输入来自stdin。您可以对其进行调整:

file="${1}"
if [ "${file}" = "-" ] ; then
    file=/dev/stdin # special device for stdin
fi

while read -r line ; do
    do something
done < "${file}"

谢谢你的回答,我将尝试一下,并对bash做进一步的研究。我仍然是这门语言的初学者:)同意的
-
通常被视为stdin。但是,应该避免使用
/dev/stdin
,因为在许多情况下,它不能按预期工作。通过强制使用
-
脚本无法从管道中读取。在某些情况下,赋值
文件=$(@vdavid当然可以在管道中使用:
cmd | tool-
。除此之外,我为什么要避免
/dev/stdin
?请详细说明那些情况
bash
保证
/dev/stdin
在用于重定向时引用标准输入,无论文件系统是否实际有这样的条目。
file=$(顺便说一句,我倾向于说“通道0”,但对于Bash来说,确切的术语是“文件描述符0”。你可以用:
lsof-a-p$$-d0
来检查当前的fd0,谢谢,伙计,我刚刚对这种语言做了一些进一步的研究,目前仍然是一个noob:p。
tool -             # reads from terminal
cmd | tool -       # used in a pipe
tool /path/to/file # reads from file