Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

linux - Bash capturing output of awk into array

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 = ' ' does not do anything and retains my original output. What change do I need to do to make this work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...