击:在脚本动态标准输入重定向 [英] Bash: redirect standard input dynamically in a script

查看:169
本文介绍了击:在脚本动态标准输入重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到这一点来决定是否标准输入重定向到文件或不:

I was trying to do this to decide whether to redirect stdin to a file or not:

[ ...some condition here... ] && input=$fileName || input="&0"
./myScript < $input

但是,这并不因为当变量$输入&放大器; 0的工作,除bash的$ P $点它作为一个文件名

But that doesn't work because when the variable $input is "&0", bash interprets it as a filename.

不过,我只是做:

if [ ...condition... ];then
    ./myScript <$fileName
else
    ./myScript

问题是,./myScript其实是我不想重复长的命令行,我也不想为它创建一个函数,因为它不是那么久或者(这是不值得的)。

The problem is that ./myScript is actually a long command line that I don't want to duplicate, nor do I want to create a function for it because it's not that long either (it's not worth it).

然后,它发生,我要做到这一点:

Then it occurred to me to do this:

[ ...condition... ] && input=$fileName || input=  #empty
cat $input | ./myScript

但需要运行多一个命令和管道(即子shell)。结果
是否有另一种更简单,更有效的方式?

But that requires to run one more command and a pipe (i.e. a subshell).
Is there another way that's simpler and more efficient?

推荐答案

所有的标准输入首先是文件描述符0(零)而不是1(这是标准输出)。

First of all stdin is file descriptor 0 (zero) rather than 1 (which is stdout).

您可以复制文件描述符或有条件使用的文件名是这样的:

You can duplicate file descriptors or use filenames conditionally like this:

[[ some_condition ]] && exec 3<$filename || exec 3<&0

some_long_command_line <&3

这篇关于击:在脚本动态标准输入重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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