How to check the exit code of a command executed by a flock?

Welcome all. I am setting up a cron job to run a bash script, and I am worried that the next one may start before the end of the previous one. A small Google search shows that a popular way to solve this problem is to use the command flockas follows:

flock -n lockfile myscript.sh
if [ $? -eq 1 ]; then
    echo "Previous script is still running!  Can't execute!"
fi

This works great. However, what should I do if I want to check the exit code myscript.sh? No matter which exit code it returns will be overwritten flock, so I don't know if it succeeded or not.

+3
source share
3 answers

, flock, flock <fd>, <fd> - . , , ( , , -n)., , , :

(
  if flock -n 200
  then
    myscript.sh
    echo $?
  fi
) 200>lockfile
+6
#!/bin/bash

if ! pgrep myscript.sh; then
  flock -n lockfile myscript.sh
fi

, , "myscript.sh" , cron . , , pgrep myscript.sh , , flock.

0

Perhaps something like this will work for you.

#!/bin/bash
RETVAL=0
lockfailed()
{
        echo "cannot flock"
        exit 1
}
(
        flock -w 2 42 || lockfailed
        false
        RETVAL=$?
        echo "original retval $RETVAL"
        exit $RETVAL
) 42>|/tmp/flocker
RETVAL=$?
echo "returned $RETVAL"
exit $RETVAL
0
source

Source: https://habr.com/ru/post/1726620/


All Articles