来自管道的 Bash 输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5710957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:48:55  来源:igfitidea点击:

Bash input from pipe

bashshellscriptingpipestdin

提问by entropo

I wrote a trivial bash script which dumps a random line from a file or STDIN:

我写了一个简单的 bash 脚本,它从文件或标准输入中随机转储一行:

#!/bin/bash
if [ $# -ne 1 ]
then
    echo "Syntax: 
echo "foo\nbar\nbaz" | randline
FILE (or \'-\' for STDIN)" echo
echo "foo\n\bar\nbaz" | randline -
- display a random line from FILE exit 1 fi RAND=`cat /proc/sys/kernel/random/uuid | cut -c1-4 | od -d | head -1 | cut -d' ' -f2` if [ != "-" ] then LINES=`cat "" | wc -l` LINE=`expr $RAND % $LINES + 1` head -$LINE | tail -1 else piped=`cat -` LINES=`echo "$piped" | wc -l` LINE=`expr $RAND % $LINES + 1` echo "$piped" | head -$LINE | tail -1 fi

However, I'd like it to also process STDIN if there are no options passed (but still fail with the help if there's no STDIN from a pipe).

但是,如果没有传递任何选项,我希望它也处理 STDIN(但如果管道中没有 STDIN,则仍然会在帮助下失败)。

That is, I'd like to say:

也就是说,我想说:

#!/bin/bash
if [ "$( tty )" == 'not a tty' ]
then
    STDIN_DATA_PRESENT=1
else
    STDIN_DATA_PRESENT=0
fi

if [[ $# -ne 1 && $STDIN_DATA_PRESENT -eq 0 ]]
then
    echo "Syntax: 
awk 'BEGIN{srand();}{printf "%04d %s\n", int(rand()*10000), ##代码##}' < $FILENAME | sort | cut -f2- -d' ' | head -1
[FILE (or \'-\' for STDIN)]" echo ##代码## - display a random line from FILE echo -e "\nWill also process piped STDIN if no arguments are given." exit 1 fi RAND=`cat /proc/sys/kernel/random/uuid | cut -c1-4 | od -d | head -1 | cut -d' ' -f2` if [[ && != "-" ]] then LINES=`cat "" | wc -l` LINE=`expr $RAND % $LINES + 1` head -$LINE | tail -1 else piped=`cat -` LINES=`echo "$piped" | wc -l` LINE=`expr $RAND % $LINES + 1` echo "$piped" | head -$LINE | tail -1 fi

... instead of ...

... 代替 ...

##代码##

How can this be done?

如何才能做到这一点?

Edit:
Thanks to Doon!

编辑:
感谢 Doon!

##代码##

采纳答案by Doon

see here ksh: how to probe stdin?it is for ksh, but an answer for bash is provided

在这里看到ksh:如何探测标准输入?它适用于 ksh,但提供了 bash 的答案

回答by Micha? ?rajer

To get random line from a file you can do:

要从文件中获取随机行,您可以执行以下操作:

##代码##

Here we do:

我们这样做:

  1. add random number to the beginning of each line
  2. sort output
  3. remove random number from the beginning of each line
  4. print first line (of mixed output)
  1. 在每一行的开头添加随机数
  2. 排序输出
  3. 从每一行的开头删除随机数
  4. 打印第一行(混合输出)

BTW, in if you are using BASH, you can use $RANDOM (provided by bash) variable instead of generating $RAND by your self.

顺便说一句,如果您使用的是 BASH,则可以使用 $RANDOM(由 bash 提供)变量而不是自己生成 $RAND。