[英]Shell Scripting: Is there a way to use variable as output instead of a file for executable?
对于像这样的命令:
/command -in input_filename -of output_filename
是否可以使用variable
而不是output_filename
我尝试过重定向,但没有用
编辑:
阅读评论和答案后,我觉得这个问题可能令人困惑。 可执行文件需要其output的文件名。 但是,我想将output保存在一个变量中。
# Declare your variable at
# some point earlier in script
variable="somevalue.txt"
.
.
.
# Use it later in script
command -f $variable
好的做法,将变量声明为只读。 这样,您就不会在脚本稍后的某个地方意外覆盖它的值。
# Declare as readonly
readonly variable="somevalue"
您不能将变量指定为输出文件,然后将其填充。
而是让程序写入stdout并捕获它。 您如何执行此操作取决于命令。 由于您未指定,因此以下是curl
的示例:
# Many programs automatically write to stdout when a file is not specified
myvar=$(curl http://stackoverflow.com)
# Many programs accept - to mean stdout for output files
myvar=$(curl -o - http://stackoverflow.com)
# Otherwise, you can often specify /dev/stdout
myvar=$(curl -o /dev/stdout http://stackoverflow.com)
如果由于命令没有干净的输出而无法执行此操作,则可能会迫使您将其写入临时文件并重新读取。
保存命令的输出:
# Capture output into variable
output="$(command -f filename)"
# Print it / do whatever you want with it
echo "$output"
编辑:
如果命令要求这种格式:
/command -in input_filename -of output_filename
但是,您还希望捕获变量中输出文件的内容,可以在完成原始命令后将输出文件读入变量。
output="$(cat output_filename)"
这将出现在原始命令之后,因为必须先编写输出文件,然后才能再次读取它。
您的问题尚不清楚,但是在最后的评论中,我想您想要这样:
#!/bin/bash
#
variable=$(./command -f $inputfile)
echo $variable
这将打印命令输出的结果。 请注意,这不存储命令的状态,而是存储输出文本(如果有)。
对于您的问题的第2版(!):
/command -in input_filename -of output_filename
如果不指定-of选项,大多数命令会将输出发送到STDOUT。 因此,请使用上面的第一种方法。
如果必须使用它,则输出必须转到文件中。 因此,在完成命令后,将文件读入变量。
variable=$(cat output_filename)
请注意,您将丢失文件的格式,希望它是单行文件。
有一种方法可以使用特殊括号来做到这一点。 我相信 {} 和反勾号(靠近 1 键)之类的
VAR1=${`cat /file`} but that's formatted incorrectly.
我不记得确切的格式,这就是我来这里的原因,但如果格式正确,这样做是可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.