bash 将命令输出存储到 shell 脚本中的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19501286/
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
store command output to array in shell script
提问by Adi
I'm using ssh to connect to a remote machine and read a log file there. From that log file, based on some tokens, I extract specific logs and store it in a variable. Every log is in new line in the log file and the data can contain any character including white space.
我正在使用 ssh 连接到远程机器并在那里读取日志文件。从该日志文件中,基于一些标记,我提取特定日志并将其存储在一个变量中。每个日志都在日志文件的新行中,数据可以包含任何字符,包括空格。
array=("$(egrep "UserComments/propagateBundle-2013-10-19--04:42:13|UserComments/propagateBundle-2013-10-19--04:38:36|UserComments/propagateBundle-2013-10-19--04:34:24" <path>/propagateBundle.log)")
echo ${array[0]}
echo "$array"
First echo prints complete output in one line separated by white space while the other prints outputs in new line. Problem, is, I'm not able to save this output as an array. I tried this:
第一个 echo 在一行中打印完整的输出,由空格分隔,而另一个在新行中打印输出。问题是,我无法将此输出保存为数组。我试过这个:
newArray=("$array")
max=${#newArray[@]}
echo $max
But echoing 'max' yields '1' on the screen. How can I save the output in an array? I also tried using
但是在屏幕上回显“max”会产生“1”。如何将输出保存在数组中?我也尝试使用
IFS=\`\n`
but could not get the data in an array.
但无法获取数组中的数据。
EDIT
编辑
I used the solution given by Anubhav and it worked like charm. Now I faced a second issue. Since my data contains white spaces, so the array broke at white spaces and wrongly contained the one comments as multiple arrays. So, I used
我使用了 Anubhav 提供的解决方案,它的效果非常好。现在我面临第二个问题。由于我的数据包含空格,所以数组在空格处中断,错误地将一个注释包含为多个数组。所以,我用
IFS=\`\n`
and also used a $
symbol before backticks. Although this solves my problem, I still get an exception in the logs:
并$
在反引号前使用了一个符号。虽然这解决了我的问题,但我仍然在日志中遇到异常:
test.sh: line 11: n: command not found
Any suggestions?
有什么建议?
采纳答案by anubhava
Don't put quotes in the command substitution:
不要在命令替换中加引号:
array=( $(egrep "UserComments/propagateBundle-2013-10-19--04:42:13|UserComments/propagateBundle-2013-10-19--04:38:36|UserComments/propagateBundle-2013-10-19--04:34:24" <path>/propagateBundle.log) )
With quotes as in your code whole output is treated as single string in the array.
在代码中使用引号将整个输出视为数组中的单个字符串。
回答by MFO
I've used IFS=('\n') otherwise all "n" chars disappears from results and sort command doesn't work properly. See bellow, it is a customized llq output.
我已经使用 IFS=('\n') 否则所有“n”字符都会从结果中消失并且排序命令无法正常工作。见下文,它是一个定制的 llq 输出。
#!/bin/bash
IFS=('\n')
raw=(`llq -f %id %o %gu %gl %st %BS %c`)
echo
echo ${raw[*]} | grep "step(s)"
echo
echo ${raw[*]} | grep "Step"
echo ${raw[*]} | grep "\---*"
echo ${raw[*]} | grep "bgp-fn*" | sort -k5 -r
echo ${raw[*]} | grep "\---*"
echo ${raw[*]} | grep "Step"
echo
echo ${raw[*]} | grep "step(s)"
echo