【问题标题】:Appending output from a command to a variable in Bash将命令的输出附加到 Bash 中的变量
【发布时间】:2015-08-12 20:59:31
【问题描述】:

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

#!/bin/bash

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

我了解如何通过使用反引号将命令的输出“捕获”到变量中。

lineInfo=`wc -l $file`

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

【问题讨论】:

  • 您实际上想做什么?我怀疑有一个更简单的方法 - 也许使用bash array
  • 你可以将lineInfo=`some_command`改为lineInfo="$lineinfo `some_command`",或者更好的使用数组。
  • 我刚刚找到了一种更简单的方法来实现我想要的结果。很抱歉给您带来麻烦。我可以只使用 wc -l *.这会给我一个我的文件计数器。

标签: bash scripting


【解决方案1】:

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

#!/bin/bash

total=""

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

echo $total

【讨论】:

  • 你也可以使用total+="$lineInfo, "
  • @chepner 谢谢,我添加了这个。
猜你喜欢
  • 2012-04-03
  • 2012-07-16
  • 2012-05-06
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
相关资源
最近更新 更多