Pulling data from multiple arrays from the same position in bash
BACKGROUND
What I am trying to do here is read from a file with PID information and split the columns into arrays. I have already finished this part, although I think this is a better way than what I have (linking the same file 4 times).
pid=( $(cat /tmp/deadpidlist.log | awk -F " " '{print $1}') )
cpu=( $(cat /tmp/deadpidlist.log | awk -F " " '{print $2}') )
mem=( $(cat /tmp/deadpidlist.log | awk -F " " '{print $3}') )
ctime=( $(cat /tmp/deadpidlist.log | awk -F " " '{print $4}') )
WHAT AM I DOING? God
After that, I need to go through each PID, and if the pid matches the criteria I'm looking for, put the appropriate cpu usage, memory usage and cpu time in it, and then submit that file.
for i in "${pid[@]}"
do
...
if grep -Fxq "$pattern" /tmp/or_report.log; then
echo "$i" >> /tmp/deadpidwalking.log
I have the rest of my code based on: https://gist.github.com/sithtoast/e1654adab3cceb137ba2
Thank!
source to share
A simple cycle in bash
should be sufficient. Note the rarely seen use of indexed arrays as arguments read
.
declare -a pid cpu mem ctime
i=-1
while ((i++)); read "pid[i]" "cpu[i]" "mem[i]" "ctime[i]" and_the_rest; do
:
done < /tmp/deadpidlist.log
A simpler loop would be
declare -a pid cpu mem ctime
while read a b c d and_the_rest; do
pid+=("$a")
cpu+=("$b")
mem+=("$c")
ctime+=("$d")
done < /tmp/deadpidlist.log
source to share
For the first part:
while read -r ipid icpu imem ictime icmd
do
pid+=($ipid)
cpu+=($icpu)
mem+=($imem)
ctime+=($ictime)
cmd+=($icmd)
done < /tmp/deadpidlist.log
Some small comments for the entity:
Use functions. You can save a lot of input by redirecting the exit from the function - for example:
some() {
echo some
cat /some/file
}
#later
some >> /some/outfile
also you can save many echo
by grouping them into oneheredoc
some2() {
cat - <<EOF
some output what want
can use $variables
$(date) #command substitutions too
EOF
}
If you don't need expansion variables, use heredoc
like<<'EOF'
Alternatively, you can use
let countertwo++ #instead of countertwo=$((countertwo + 1))
source to share
Use associative arrays for cpu, mem and ctime. Also, read the input in just one pass through the inline read
.
declare -a pid
declare -A cpu
declare -A mem
declare -A ctime
while read this_pid this_cpu this_mem this_ctime tail; do
pid[${#pid[*]}]=$this_pid
cpu[$this_pid]=$this_cpu
mem[$this_pid]=$this_mem
ctime[$this_pid]=$this_ctime
done < /tmp/deadpidlist.log
for i in "${pid[@]}" do;
# ...
echo $i cpu[$i] mem[$i] ctime[$i]
done
source to share