Home > other >  Script Bash : lfor loop in file
Script Bash : lfor loop in file

Time:05-21

I try from this command

ps axr -o pid,time,command | grep batch_file.php > /tmp/view-process

which returns me :

21861 00:13:30 php -q batch_file.php

in file /tmp/view-process

After that, I run these 3 commands :

PID=$(awk -F " " '{ print $1 }' /tmp/view-process)
TIME=$(awk -F " " '{ print $2 }' /tmp/view-process)
DIR=$(pwdx $PID > /tmp/view-process)
DIR=$(awk -F "/" '{ print $6 }' /tmp/view-process)

in order to be able to retrieve only the pid in the variable $PID, only the time in $TIME and only the path of the current process in $DIR

I tried several ways to do a for loop or an array in order to display only 1 PID DIR TIME on a line and display the second PID etc on a second line.

I only managed to do it this way : 21861 - proc_1 - 00:25:01 (for 1 pid it's work, but for 2 and more it didn't work. It's displays like this : 21861 23776 - proc_1 proc_2 - 00:12:02

Therefore I do not find how to do with the for loop and my file in order to arrive at my result

Do you have any ideas ?

CodePudding user response:

Let's do this without a temp file.

I'm going to use bash associative arrays and process substitutions

declare -A times dirs

while read -r pid time cmd; do
    times[$pid]=$time
done < <(
    ps axr -o pid,time,command | grep batch_file.php
)

while IFS=': /' read -r pid _ _ _ _ _ dir _; do
    dirs[$pid]=$dir
done < <(
    pwdx "${!times[@]}"
)

for pid in "${!times[@]}"; do
    echo "$pid - ${times[$pid]} - ${dirs[$pid]}"
done
  • Related