Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing jps output into array

Tags:

bash

process

I'm using jps in a bash shell to find all running java processes. I want to be able to use the list of PIDs that is output by jps. I can successfully print them to the screen using

jps | awk '{print $1}'

but I expect more than one process to be running and I would like to put them in an array. I found another example where they used

awk '{arr[$1]}'

because the output that they wanted in the array was a single column. This is similar to the column of PIDs that I want put into an array.

Is it possible to pipe them into an array? I'm having trouble getting the index of the array to change when needed. Is there a better way to do this?

Any guidance would be warmly received. Thanks.

like image 692
ebeth Avatar asked Jul 13 '26 20:07

ebeth


1 Answers

Based on your first example, you should be able to capture all process IDs in a bash array using

pids=( $(jps | awk '{print $1}') )

Once in the array, they can be iterated over:

for pid in "${pids[@]}"; do
     echo $pid
done

or accessed individually

echo "${pids[0]}"
echo "${pids[1]}"

The total number stored in the array is found with ${#pids[@]}.

like image 163
chepner Avatar answered Jul 15 '26 11:07

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!