1

I'd like to create a function that will wait until a job is completed before starting a new process. I'm aware of the wait command that is built into bash, but it only works for child processes. It will fail if I start in a different bash session. I wrote a bash function using kill -0 that takes a pid and waits until the given process completes. However, it doesn't seem to work. Say the pid of a particular job sleep 60 & is 4569, when I type ./pidwait.sh 4569, nothing prints out. What am I doing wrong?

#!/usr/bin/env bash

function pidwait()
{
    while kill -0 "$1"; do
        echo "Process $1 still running..."
        sleep 1
    done
    echo 'Process $1 is done'
}

1 Answer 1

3

You are creating a function in your script but never using it. You could source that script and then call pidwait 4569 (no ./) or add a call to the function inside the script:

#!/usr/bin/env bash

function pidwait()
{
    while kill -0 "$1"; do
        echo "Process $1 still running..."
        sleep 1
    done
    echo "Process $1 is done"
}

pidwait "$1"

Additionally the use of single quotes in your second echo command will cause the literal $1 to be printed out instead of the value of the first parameter.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .