array length in ksh always return 1 and why array is not lines

蹲街弑〆低调 提交于 2019-12-10 22:23:28

问题


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

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

instead of

 0 S  s157759 22594   1   0  50 20  ?  62628  ? 11:14:06 ?  2:06 /usr/lib/firefox/firefox-bin

in one line

I want to create an array with lines, not words.


回答1:


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}')

with

arr=( $(ps -elf | nawk -v pattern=${userid} '{if ($3==pattern) print}') )

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


来源:https://stackoverflow.com/questions/15485096/array-length-in-ksh-always-return-1-and-why-array-is-not-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!