ksh:如何探测stdin? [英] ksh: how to probe stdin?

查看:82
本文介绍了ksh:如何探测stdin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的ksh脚本具有不同的行为,具体取决于是否有通过stdin传入的内容:

I want my ksh script to have different behaviors depending on whether there is something incoming through stdin or not:

    (1) cat file.txt | ./script.ksh  (then do "cat <&0 >./tmp.dat" and process tmp.dat)
vs. (2) ./script.ksh (then process $1 which must be a readable regular file)

检查stdin是否为终端[-t 0]并没有帮助,因为我的脚本是从其他脚本调用的.

Checking for stdin to see if it is a terminal[ -t 0 ] is not helpful, because my script is called from an other script.

如果stdin为空"(第二种情况),则执行"cat& 0> ./tmp.dat"以检查tmp.dat的大小是否挂起,以等待stdin中的EOF.

Doing "cat <&0 >./tmp.dat" to check tmp.dat's size hangs up waiting for an EOF from stdin if stdin is "empty" (2nd case).

如何仅检查stdin是否为空"?!

How to just check if stdin is "empty" or not?!

推荐答案

您正在HP-UX上运行

在HP-UX上经过测试[ -t 0 ],它似乎对我有用.我使用了以下设置:

Tested [ -t 0 ] on HP-UX and it appears to be working for me. I have used the following setup:

/tmp/x.ksh:

#!/bin/ksh
/tmp/y.ksh

/tmp/y.ksh:

#!/bin/ksh
test -t 0 && echo "terminal!"

运行/tmp/x.ksh打印:terminal!

您能否在您的平台上确认以上内容,和/或提供更紧密地反映您的情况的替代测试设置?您的脚本最终是否由cron产生?

Could you confirm the above on your platform, and/or provide an alternate test setup more closely reflecting your situation? Is your script ultimately spawned by cron?

编辑2

如果不顾一切,并且Perl可用,请定义:

If desperate, and if Perl is available, define:

stdin_ready() {
  TIMEOUT=$1; shift
  perl -e '
    my $rin = "";
    vec($rin,fileno(STDIN),1) = 1;
    select($rout=$rin, undef, undef, '$TIMEOUT') < 1 && exit 1;
  '
}

stdin_ready 1 || 'stdin not ready in 1 second, assuming terminal'


编辑3

请注意,如果您的输入来自sortssh等,则超时可能需要很大.(所有这些程序都可以在几秒钟或几分钟内生成并使用脚本建立管道,然后再生成任何数据. )此外,如果输入中没有任何内容(例如终端),则使用大量超时可能会严重破坏脚本.

Please note that the timeout may need to be significant if your input comes from sort, ssh etc. (all these programs can spawn and establish the pipe with your script seconds or minutes before producing any data over it.) Also, using a hefty timeout may dramatically penalize your script when there is nothing on the input to begin with (e.g. terminal.)

如果可能存在很大的超时问题,并且可以影响脚本的调用方式,则可以通过自定义选项或通过自定义选项来强制调用方明确指示程序是否应使用stdin.标准的GNUtar方式(例如,脚本[options [-]] FILE ...,其中FILE可以是文件名,用于表示标准输入的-或其组合),以及您的脚本如果将-作为参数传递,则只能从标准输入中读取.)

If potentially large timeouts are a problem, and if you can influence the way in which your script is called, then you may want to force the callers to explicitly instruct your program whether stdin should be used, via a custom option or in the standard GNU or tar manner (e.g. script [options [--]] FILE ..., where FILE can be a file name, a - to denote standard input, or a combination thereof, and your script would only read from standard input if - were passed in as a parameter.)

这篇关于ksh:如何探测stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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