首页 > 解决方案 > bsub 命令内的输出重定向

问题描述

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

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

目前此 bsub 执行失败。此外,我试图逃避重定向符号和括号的尝试都失败了,例如:

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

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

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

然后它确实会正确执行(没有错误)。然而,我有兴趣在更组合的命令的上下文中实现输出“<”的重定向,并且在这里将这个简单的命令作为示例。

标签: bashunix

解决方案


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


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

# 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

推荐阅读