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.
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[@]}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With