将命令的输出附加到 Bash 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31962633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:25:09  来源:igfitidea点击:

Appending output from a command to a variable in Bash

bashscripting

提问by Bobby

I'm trying to append an output of a command to a variable in Bash. My code is

我正在尝试将命令的输出附加到 Bash 中的变量。我的代码是

#!/bin/bash

for file in *
do
    lineInfo=`wc -l $file`
    echo "$lineInfo"
done

I understand how to "capture" the output of a command to a variable as I have done in this line by the use of backquotes.

我了解如何通过使用反引号将命令的输出“捕获”到变量,就像我在这一行中所做的那样。

lineInfo=`wc -l $file`

Is there a clean cut way I can place the output of that entire for loop into a variable in Bash? Or in each iteration of the for loop append the output of the wc command to linesInfo ? (Without redirecting anything to files) Thanks.

有没有一种简洁的方法可以将整个 for 循环的输出放入 Bash 中的变量中?或者在 for 循环的每次迭代中将 wc 命令的输出附加到 linesInfo ?(不将任何内容重定向到文件)谢谢。

回答by geckon

This stores all the line infos (separated by commas) into one variable and prints that variable:

这将所有行信息(以逗号分隔)存储到一个变量中并打印该变量:

#!/bin/bash

total=""

for file in *
do
    lineInfo=`wc -l $file`
    total="$total$lineInfo, "  # or total+="$lineInfo, "
done

echo $total