我有一个脚本'myscript',输出如下:
abc
def
ghi
在另一个脚本中,我调用:
declare RESULT=$(./myscript)
$RESULT获取值
abc def ghi
是否有一种方法来存储结果与换行符,或与'\n'字符,所以我可以输出它与'echo -e'?
我有一个脚本'myscript',输出如下:
abc
def
ghi
在另一个脚本中,我调用:
declare RESULT=$(./myscript)
$RESULT获取值
abc def ghi
是否有一种方法来存储结果与换行符,或与'\n'字符,所以我可以输出它与'echo -e'?
当前回答
如果你对特定的行感兴趣,使用result-array:
declare RESULT=($(./myscript)) # (..) = array
echo "First line: ${RESULT[0]}"
echo "Second line: ${RESULT[1]}"
echo "N-th line: ${RESULT[N]}"
其他回答
实际上,RESULT包含了您想要演示的内容:
echo "$RESULT"
你所展示的就是你所得到的:
echo $RESULT
As noted in the comments, the difference is that (1) the double-quoted version of the variable (echo "$RESULT") preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $RESULT) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).
这样做的另一个缺陷是命令替换- $()-删除尾随换行符。可能并不总是重要的,但如果你真的想保留输出的内容,你必须使用另一行和一些引用:
RESULTX="$(./myscript; echo x)"
RESULT="${RESULTX%x}"
如果您想处理所有可能的文件名(以避免在错误的文件上操作等未定义的行为),这一点尤其重要。
这个怎么样,它将每一行读入一个变量,然后可以使用! 假设myscript输出被重定向到一个名为myscript_output的文件
awk '{while ( (getline var < "myscript_output") >0){print var;} close ("myscript_output");}'
除了@l0b0给出的答案之外,我还遇到了这样的情况:我需要保留脚本输出的任何尾随换行符,并检查脚本的返回代码。 和l0b0的答案的问题是'echo x'重置$?回到零…所以我想出了这个非常狡猾的解决方案:
RESULTX="$(./myscript; echo x$?)"
RETURNCODE=${RESULTX##*x}
RESULT="${RESULTX%x*}"
如果你对特定的行感兴趣,使用result-array:
declare RESULT=($(./myscript)) # (..) = array
echo "First line: ${RESULT[0]}"
echo "Second line: ${RESULT[1]}"
echo "N-th line: ${RESULT[N]}"