命令中的输出重定向

命令中的输出重定向

本文介绍了bsub 命令中的输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 bsub 命令中使用输出重定向,例如:

Is it possible to use output redirection inside bsub command such as:

bsub -q short "cat <(head -2 myfile.txt) > outputfile.txt"

目前这个 bsub 执行失败.另外我试图转义重定向标志和括号都失败了,例如:

Currently this bsub execution fails. Also my attempts to escape the redirection sign and the parenthesis were all failed, such as:

bsub -q short "cat \<\(head -2 myfile.txt\) > outputfile.txt"
bsub -q short "cat <\(head -2 myfile.txt\) > outputfile.txt"

*注意,我很清楚这个简单命令中的重定向不是必需的,因为该命令可以很容易地写成:

*Note, I'm well aware that the redirection in this simple command is not necessary as the command could easily be written as:

bsub -q short "head -2 myfile.txt > outputfile.txt"

然后它确实会正确执行(没有错误).然而,我对实现输出 '<' 的重定向感兴趣在更复杂的命令的上下文中,我将这个简单的命令仅作为示例.

and then it would indeed be executed properly (without errors). I am however interested in implementing the redirection of output '<' within the context of a more composed command, and am bringing this simple command here as an example only.

推荐答案

<(...)进程替换 -- 一个在基线上不可用的 bash 扩展POSIX 外壳.system()subprocess.Popen(..., shell=True) 和类似的调用使用 /bin/sh,这是不保证的有这样的扩展.

<(...) is process substitution -- a bash extension not available on baseline POSIX shells. system(), subprocess.Popen(..., shell=True) and similar calls use /bin/sh, which is not guaranteed to have such extensions.

作为一种适用于任何可能的命令而无需担心如何将其正确转义为字符串的机制,您可以通过环境导出该函数及其使用的任何变量:

As a mechanism that works with any possible command without needing to worry about how to correctly escape it into a string, you can export that function and any variables it uses through the environment:

# for the sake of example, moving filenames out-of-band
in_file=myfile.txt
out_file=outputfile.txt

mycmd() { cat <(head -2 <"$in_file") >"$out_file"; }

export -f mycmd                # export the function into the environment
export in_file out_file        # and also any variables it uses

bsub -q short 'bash -c mycmd'  # ...before telling bsub to invoke bash to run the function

这篇关于bsub 命令中的输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:22