📖 Scenario: You want to run a script that should only have one copy running at a time. To do this, you will use a lock file. This lock file will tell the script if another copy is already running, so it won't start twice.
🎯 Goal: Build a bash script that creates a lock file when it starts. If the lock file exists, the script will stop and tell the user another instance is running. If not, it will create the lock file, run the main task, then remove the lock file at the end.
📋 What You'll Learn
Create a variable for the lock file path
Check if the lock file exists
Create the lock file if it does not exist
Remove the lock file after the main task
Print a message if another instance is running
💡 Why This Matters
🌍 Real World
Lock files are used in scripts that should not run multiple times at once, like backups or updates, to avoid conflicts.
💼 Career
Many system administrators and automation engineers use lock files to ensure safe script execution without overlap.
Progress0 / 4 steps
1
Create a lock file variable
Create a variable called lockfile and set it to /tmp/myscript.lock.
Bash Scripting
Hint
Use = to assign the string /tmp/myscript.lock to the variable lockfile.
2
Check if the lock file exists
Add an if statement to check if the file at $lockfile exists using test -e. If it exists, print "Another instance is running." and exit the script with status 1.
Bash Scripting
Hint
Use if test -e "$lockfile"; then to check if the file exists.
3
Create the lock file and simulate main task
Create the lock file by using touch on $lockfile. Then simulate the main task by printing "Script is running..." and sleeping for 2 seconds.
Bash Scripting
Hint
Use touch "$lockfile" to create the lock file.
4
Remove the lock file and print completion
Remove the lock file using rm on $lockfile. Then print "Script finished and lock released.".
Bash Scripting
Hint
Use rm "$lockfile" to remove the lock file.
Practice
(1/5)
1. What is the main purpose of using a lock file in a bash script?
easy
A. To prevent multiple instances of the script from running at the same time
B. To speed up the script execution
C. To store user input temporarily
D. To log errors during script execution
Solution
Step 1: Understand the role of a lock file
A lock file is used to signal that a script is already running, preventing duplicates.
Step 2: Identify the main purpose
This prevents multiple script instances from running simultaneously, avoiding conflicts.
Final Answer:
To prevent multiple instances of the script from running at the same time -> Option A