File Locking in Shell

Level 4173 keystrokes

A lock file keeps a second copy of the script from running at the same time: if the file exists the script stops, otherwise it creates the file and a trap removes it on exit. The check and the creation are separate steps, so this is not fully race-free.

Shell code

# Path of the lock file
1LOCKFILE="/tmp/myapp.lock"
# If the lock file exists, another instance is probably running
2if [ -f "$LOCKFILE" ]; then
3 echo "Script already running"
# Stop with a non-zero status
4 exit 1
5fi
# Create the lock file and write this shell's PID ($$) into it
6echo $$ > "$LOCKFILE"
# Remove the lock file when the script exits
7trap "rm -f $LOCKFILE" EXIT
# The main work, done while holding the lock
8echo "Processing..."
9sleep 2

Output

Processing...
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 12
  • $× 5
  • .× 4
  • -× 2
  • /× 2
  • ;× 1
  • [× 1
  • ]× 1
  • =× 1
  • >× 1

More Shell examples at level 4

← Shell typing practice