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 file1LOCKFILE="/tmp/myapp.lock"# If the lock file exists, another instance is probably running2if [ -f "$LOCKFILE" ]; then3 echo "Script already running" # Stop with a non-zero status4 exit 15fi# Create the lock file and write this shell's PID ($$) into it6echo $$ > "$LOCKFILE"# Remove the lock file when the script exits7trap "rm -f $LOCKFILE" EXIT# The main work, done while holding the lock8echo "Processing..."9sleep 2Output
Processing...
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