touch (create empty file or update timestamp)
The touch command serves two primary purposes: creating a new, empty file if it doesn't already exist, or updating the access and modification timestamps of an existing file or directory. It is frequently used for managing file ages and in scripting.
Example 1: Create a single empty file
# Create a new, zero-byte file named 'new_script.sh'
touch new_script.sh
Explanation: If new_script.sh does not exist in the current directory, this command will create it. The file will be empty and have its ownership and permissions set based on system defaults.
Example 2: Create multiple empty files
# Create three new empty files simultaneously
touch file1.txt file2.txt file3.log
Explanation: You can create several files at once by listing their names after the touch command. This is more efficient than issuing the command multiple times.
Example 3: Update the timestamp of an existing file
# Update the access and modification times of 'existing_file.txt' to the current time
touch existing_file.txt
Explanation: If existing_file.txt already exists, this command will not alter its content. Instead, it will update the file's last access and last modification timestamps to the current system time.
Example 4: Do not create a new file
# Update the timestamp of 'config.yml' only if it already exists; do not create it
touch -c config.yml
Explanation: The -c or --no-create option is useful in scripts to ensure touch only modifies existing files. It prevents the command from creating a new file if one by that name does not exist.
Example 5: Set a specific timestamp for a file
# Set the modification time of 'archive.zip' to 10:30:00 on June 22, 2025
touch -d "2025-06-22 10:30:00" archive.zip
Explanation: The -d (date) option allows you to set a file's timestamp to a specific date and time provided in a string format, rather than the current time. This is useful for file organization and for build systems that rely on file modification times.
Example 6: Use the timestamp of another file
# Set the timestamp of 'file_a' to be the same as 'file_b'
touch -r file_b file_a
Explanation: The -r (reference) option is a convenient way to apply the timestamps of a source file (file_b) to a destination file (file_a). This synchronizes the modification and access times of the two files.
Example 7: Create a file with a space in its name
# Create a new empty file named 'important notes.txt'
touch "important notes.txt"
Explanation: To create a file with spaces in its name, the filename must be enclosed in quotes. This ensures the shell interprets the multi-word string as a single filename.