65

I am stuck on a little problem. I have a command which pipes output to awk but I want to capture the output of to an array one by one.

My example:

myarr=$(ps -u kdride | awk '{ print $1 }')

But that capture all my output into one giant string separated by commas:

output: PID 3856 5339 6483 10448 15313 15314 15315 15316 22348 29589 29593 32657 1

I also tried the following:

IFS=","
myarr=$(ps -u kdride | awk '{ print $1"," }')

But the output is: PID, 3856, 5339, 6483, 10448, 15293, 15294, 15295, 15296, 22348, 29589, 29593, 32657,
1

I want to be able to capture each individual pid into its own array element. Setting IFS = '\n' does not do anything and retains my original output. What change do I need to do to make this work?

1
  • You can skip the awk command altogether by using myarr=( $(ps -u kdride -o pid) ). (Note the extra parenthesis as pointed out in Paul's answer). Commented Feb 27, 2013 at 13:56

2 Answers 2

114

Add additional parentheses, like this:

myarr=($(ps -u kdride | awk '{ print $1 }'))

# Now access elements of an array (change "1" to whatever you want)
echo ${myarr[1]}

# Or loop through every element in the array
for i in "${myarr[@]}"
do
   :
  echo $i
done

See also bash — Arrays.

Sign up to request clarification or add additional context in comments.

7 Comments

Ah much thanks. I skipped over that part entirely. Reference helps much thanks
What is the point of the : after the do? Why do we need a true here? I ran it without it and it still worked?
I am also curious why there is a :
I am also curious why there is a : please let us know
Has anyone came to verdict on why there is a random colon?
|
7

Use Bash's builtin mapfile (or its synonym readarray)

mapfile -t -s 1 myarr < <(ps -u myusername | awk '{print $1}')

At least in GNU/Linux you can format output of ps, so no need for awk and -s 1

mapfile -t myarr < <(ps -u myusername -o pid=)

3 Comments

why do you need to use < twice?
@baggiponte It is because I am redirecting process substitution
not available on the MAC OSX version of bash unfortunately though...

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.