在KSH数组长度始终返回1,为什么数组不线 [英] array length in ksh always return 1 and why array is not lines
问题描述
我要呼应过程的信息在KSH一个UID:
I need to echo information of a process for a UID in ksh:
#!/bin/ksh
read userid
arr=$(ps -elf | nawk -v pattern=${userid} '{if ($3==pattern) print}')
arrlen=${#arr[@]}
echo $arrlen
for f in "${arr[@]}"; do
echo $f
done
改编过程是为这个UID的数组。
arrlen总是等于1。
为什么?
我的第二个问题:
我尝试回声所有元素ARR和输出
arr is an array of process for this UID. arrlen always equal 1. Why? My second question: I try to echo all elements in arr and output is
0
S
s157759
22594
1
0
50
20
?
2:06
/usr/lib/firefox/firefox-bin
而不是
0 S s157759 22594 1 0 50 20 ? 62628 ? 11:14:06 ? 2:06 /usr/lib/firefox/firefox-bin
在同一行
我想创建一个行,而不是单词的数组。
I want to create an array with lines, not words.
推荐答案
您不能创建一个数组;要创建新行分隔值的字符串。替换
You aren't creating an array; you're creating a string with newline-separated values. Replace
arr=$(ps -elf | nawk -v pattern=${userid} '{if ($3==pattern) print}')
与
arr=( $(ps -elf | nawk -v pattern=${userid} '{if ($3==pattern) print}') )
然而,这仍然留下您与该阵列将对待每行的每个字段从 PS
作为一个单独的元件的问题。更好的方法是使用来自 PS
阅读目录读
内置:
However, this still leaves you with the problem that the array will treat each field of each line from ps
as a separate element. A better solution is to read directory from ps
using the read
built-in:
ps -elf | while read -a fields; do
if [[ ${fields[2]} = $userid ]]; then
continue
fi
echo "${fields[@]}"
done
这篇关于在KSH数组长度始终返回1,为什么数组不线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!