0

I am creating a script using ksh where a process (simple_script.sh) is executed and iterates 5 times. What I need to do is get the pid each time the process is executed and store them in an array. So far I can get the script to execute simple_script.sh 5 times,but have been unable to get the pid's into an array.

while [ "$i" -lt 5 ]
do
        ./simple_script.sh
        pids[$i]=$!
        i=$((i+1))
done
hanktank45
  • 19
  • 3
  • $! is used to get the PID of the last BACKGROUND process. Hence if you put a "&" after the call to your simple script, you will have all 5 PIDs. – Andre Gelinas Mar 21 '19 at 00:44

1 Answers1

0

As Andre Gelinas said, $! stores the pid of the last backgrounded process.

If you are okay with all of the commands executing in parallel, you can use this

#!/bin/ksh

i=0
while [ "$i" -lt 5 ]
do
        { ls 1>/dev/null 2>&1; } &
        pids[$i]=$!
        i=$((i+1))
        # print the index and the pids collected so far
        echo $i
        echo "${pids[*]}"
done

And the result will look something like this:

1
5534
2
5534 5535
3
5534 5535 5536
4
5534 5535 5536 5537
5
5534 5535 5536 5537 5538

If you want to execute the commands serially, you can use wait.

#!/bin/ksh

i=0
while [ "$i" -lt 5 ]
do
        { ls 1>/dev/null 2>&1; } &
        pids[$i]=$!
        wait
        i=$((i+1))
        echo $i
        echo "${pids[*]}"
done
Greg Nisbet
  • 6,710
  • 3
  • 25
  • 65