array length in ksh always return 1 and why array

2019-07-14 18:47发布

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条回答
放我归山
2楼-- · 2019-07-14 19:37

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
查看更多
登录 后发表回答