繁体   English   中英

如果没有文件,则从stdin读取linux shell脚本

[英]linux shell script read from stdin if no file

我试图将我的Linux Shell脚本设置为从文件中读取(我正在工作),但是如果没有任何文件,则需要从stdin中读取。

读取文件的命令如下所示:

./stats -row test_file

我将如何读取用户输入的内容,如下所示:

./stats -row 4 2 3 5 3 4 5 3 6 5 6 3 4

当我输入这样的命令时,我得到“没有这样的文件或目录”

我将脚本分解为需要帮助的问题。

#!/bin/sh

INPUT_FILE=$2         #Argument 2 from command line is the input file
exec 5< $INPUT_FILE   #assign input file to file descriptor #5

while read -u 5 line  #read from file descriptor 5 (input file)
do
    echo "$line"
done

exec 5<&-   #close file descriptor #5

这对于我需要的输入也不起作用。

while read line  
do
    echo "$line"
done <$2

巧妙的解决方案

一个非常熟练的if语句可以解决问题:

INPUT_FILE=$2         #Argument 2 from command line is the input file

if [ -f "$INPUT_FILE" ]; then

    while read -r line
    do
        echo "$line"
    done <"$INPUT_FILE"

else

    while read -r line
    do
        echo "$line"
    done

fi

注意:假设您仍在寻找文件名作为第二个参数。


巧妙的解决方案

我不能相信,但是这里已经回答了artful解决方案: 如何从bash中的文件或stdin中读取?

INPUT_FILE=${2:-/dev/stdin}         #Argument 2 from command line is the input file

while read -r line
do
    echo "$line"
done <"$INPUT_FILE"

exit 0

我正在INPUT_FILES类似的解决方案,但是错过了stdin设备/dev/stdin作为INPUT_FILES的默认INPUT_FILES 请注意,此解决方案仅限于具有proc文件系统的OS。

在bash脚本中,我通常将从文件(或管道)中读取的代码放入函数中,该函数可以将重定向与逻辑分开。

另外,从文件或STDIN读取数据时,逻辑不要理会哪个是一个好主意。 因此,最好将STDIN捕获到一个临时文件中,然后其余文件读取代码相同。

这是一个示例脚本,该脚本从ARG 1或STDIN读取,仅计算文件中的行数。 它还在同一输入上调用wc -l并显示两种方法的结果。

#!/bin/bash

# default input is this script
input=$0

# If arg given, read from it
if (( $# > 0 )); then
  input=$1
  echo 1>&2 "Reading from $input"
else
  # otherwise, read from STDIN
  # since we're reading twice, need to capture it into
  # a temp file
  input=/tmp/$$.tmp
  cat >$input
  trap "rm -f $input" EXIT ERR HUP INT QUIT
  echo 1>&2 "Reading from STDIN (saved to $input)"
fi

count_lines() {
  local count=0
  while read line ; do
    let count+=1
  done
  echo $count
}

lines1=`count_lines <$input`
lines2=`wc -l <$input`

fmt="%15s: %d\n"
printf "$fmt" 'count_lines' $lines1
printf "$fmt" 'wc -l'       $lines2

exit

这是两个调用:一个调用arg 1上的文件,另一个不带参数的调用,从STDIN读取:

$ ./t2.sh t2.sh
Reading from t2.sh
    count_lines: 35
          wc -l: 35

$ ./t2.sh <t2.sh
Reading from STDIN (saved to /tmp/8757.tmp)
    count_lines: 35
          wc -l: 35

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM