Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am using Ubuntu 12.0.4 I have a script basically with the following codes:

lockfile=/var/tmp/mylock

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; then
    exit_normally "instance is running"
else
    echo "no instance is running"
fi

The file /var/tmp/mylock doesn't exists in my system, so when I execute my script manually I get "no instance is running" which is correct.

But when the shell script is executed by cron, it always return "instance is running"

I am not sure where to check or what to look for to find the root cause for the problem above, hopefuly I can get a few pointers here..

share|improve this question
3  
Not sure the answer, but it'll boil down to environmental. As a general point on problems like these, you might try to break it apart into separate pieces in the same temporary/test/one-time script, echo plenty of return codes and don't suppress any errors. For example, take the subshell commands, execute each individually then echo $? after each and then once again altogether as a subshell and echo $? that as well. Something will jump out at you. You can schedule that as a one time cronjob and examine the email generated. –  Joel Davis Jun 7 '13 at 12:22
1  
Is it the same shell in both cases? Try this: ( set -o noclobber; echo $? > "$ecfile"; shopt > "$debugfile"; echo "$SHELL";) –  Hauke Laging Jun 7 '13 at 14:20
1  
Just explicitly force a shell through a shebang line ( #!/bin/bash ) or by using bash /your/path/and/file) –  Anthon Jun 7 '13 at 14:22
1  
Post the full script. Also, add set -x at the top of the script just below the #! line, run the script from the command line, run the script from cron, and post both resulting traces. –  Gilles Jun 7 '13 at 22:30

1 Answer 1

As a general practice, creating a file and expecting the OS to not clobber it if it exists isn't a good way to test if it exists.

You'd be better served with:

if [ -f $lockfile ]; then
  exit_normally "instance is running"
else
  echo "no instance is running"
fi

However, if you're trying to use the existence of a file as a lockfile, you'd probably be better off using the unix lockfile command:

lockfile -r 0 $lockfile
if [ $? -ne 0 ]; then
  exit_normally "instance is running"
else
  echo "no instance is running"
fi
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.