如何从在bash文件或标准输入读取? [英] How to read from file or stdin in bash?

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

问题描述

在Perl以下code会从命令行参数,或从标准输入指定的文件中读取?

In Perl the following code will read from file specified on command line args or from stdin?

while (<>) {
   print($_);
}

这是很方便的。我只是想知道什么是从在bash文件或标准输入读取简单的方法。

This is very convenient. I just want to know what's the simplest way to read from file or stdin in bash.

推荐答案

下面的解决方案从文件中读取,如果调用脚本
用文件名作为从标准输入第一个参数$ 1 其它。

The following solution reads from a file if the script is called with a file name as the first parameter $1 otherwise from standard input.

while read line
do
  echo "$line"
done < "${1:-/dev/stdin}"

在替换 $ {1:-...} 需要 $ 1 如果已定义,否则
使用自己的过程的标准输入的文件名

The substitution ${1:-...} takes $1 if defined otherwise the file name of the standard input of the own process is used.

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

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