Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid command errors in shell script execution

Tags:

bash

shell

ksh

I have a block of code in a shell script as follows..

    run_checks()
    {
    # Check if program is already running
    if ! mkdir /tmp/aisync.lock; then
      printf "Failed to aquire lock.\n" >&2
      exit 1
    fi
    trap 'rm -rf /tmp/aisync.lock' EXIT
    }

It basically checks if aisync.lock exists and fails if it does, to prevent multiple instances of the same shell script from running.

However, if I run this from the console i get..

    # syncai.sh
    mkdir: 0653-358 Cannot create /tmp/aisync.lock.
    /tmp/aisync.lock: Do not specify an existing file.
    Failed to aquire lock.

Is there a way to avoid the error?

    mkdir: 0653-358 Cannot create /tmp/aisync.lock.
    /tmp/aisync.lock: Do not specify an existing file.

So that it looks more clean when I run it from command line.. I know that if I cron it I can send everything to /dev/null which I intend to do.. but running manually from console how can I remove those errors from printing out?

Thanks.


1 Answers

You can change the middle part of your script like this:

if ! mkdir /tmp/aisync.lock 2>/dev/null; then
  printf "Failed to aquire lock.\n" >&2
  exit 1
fi

That way the error message from mkdir will be thrown away. At the same time the behavior is unchanged, mkdir still fails, so the condition in the if will evaluate true and the script will exit with 1.

like image 160
janos Avatar answered Jan 28 '26 12:01

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!