我需要将脚本中的命令输出读入数组.该命令例如是:
ps aux | grep | grep | x
Run Code Online (Sandbox Code Playgroud)
并且它按行给出输出,如下所示:
10
20
30
Run Code Online (Sandbox Code Playgroud)
我需要将命令输出中的值读入数组,然后如果数组的大小小于3,我将做一些工作.
gni*_*urf 116
其他答案将打破,如果命令的输出包含空格(这是相当常见的)或水珠字符,如*,?,[...].
要在数组中获取命令的输出,基本上有两种方法:
使用Bash≥4使用-it mapfile是最有效的:
mapfile -t my_array < <( my_command )
Run Code Online (Sandbox Code Playgroud)否则,循环读取输出(较慢但安全):
my_array=()
while IFS= read -r line; do
my_array+=( "$line" )
done < <( my_command )
Run Code Online (Sandbox Code Playgroud)你可能会看到很多这样的东西:
my_array=( $( my_command) )
Run Code Online (Sandbox Code Playgroud)
但是不要用它!看看它是如何破碎的:
$ # this is the command used to test:
$ echo "one two"; echo "three four"
one two
three four
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # Not good! now look:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!
Run Code Online (Sandbox Code Playgroud)
然后有人会建议IFS=$'\n'用来解决这个问题:
$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!
Run Code Online (Sandbox Code Playgroud)
但现在让我们使用另一个命令:
$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?
Run Code Online (Sandbox Code Playgroud)
那是因为我t在当前目录中调用了一个文件...这个文件名与glob 匹配[three four]...此时有些人会建议使用它set -f来禁用globbing:但是看看它:你必须改变IFS并使用set -f它来修复一个破碎的技术(你甚至没有修复它)!在这样做的时候,我们真的要对抗 shell,而不是使用shell.
$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'
Run Code Online (Sandbox Code Playgroud)
在这里我们正在使用shell!
Mic*_*per 77
您可以使用
my_array=( $(<command>) )
Run Code Online (Sandbox Code Playgroud)
将命令输出存储<command>到数组中my_array.
您可以使用访问该数组的长度
my_array_length=${#my_array[@]}
Run Code Online (Sandbox Code Playgroud)
现在长度存储在my_array_length.
想象一下,您要将文件和目录名称(在当前文件夹下)放入数组并计算其项目.脚本就像;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Run Code Online (Sandbox Code Playgroud)
或者,您可以通过添加以下脚本来迭代此数组:
for element in "${my_array[@]}"
do
echo "${element}"
done
Run Code Online (Sandbox Code Playgroud)