2

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.