mkdir / rmdir / touch
mkdir creates directories, rmdir removes empty directories, and touch creates files or updates their timestamps. These commands are commonly used when setting up files and directories.
Syntax
mkdir [options] directory rmdir [options] directory touch [options] file
Options
| Command / Option | Description |
|---|---|
| mkdir directory | Creates a directory. |
| mkdir -p path | Creates the directory and all intermediate parent directories. Does not return an error if the directory already exists. |
| mkdir -m mode directory | Sets the permission mode when creating the directory (e.g., mkdir -m 755 dir). |
| rmdir directory | Removes an empty directory. Returns an error if the directory contains files. |
| rmdir -p path | Removes empty directories recursively along the specified path. |
| touch file | Creates an empty file if it does not exist. If it already exists, updates its last-modified timestamp to the current time. |
| touch -t datetime file | Sets the timestamp to a specified date and time (format: [[CC]YY]MMDDhhmm[.ss]). |
| touch -a file | Updates only the access time. |
| touch -m file | Updates only the modification time. |
Sample Code
The following examples use this directory structure.
Create a directory.
mkdir project ls empty_dir project
Create multiple directories at once.
mkdir src tests docs ls docs empty_dir project src tests
Create a nested directory structure in one step. With -p, any missing intermediate directories are created automatically.
mkdir -p project/src/components ls project/src/ components
Create empty files.
touch index.html style.css script.js ls docs empty_dir index.html project script.js src style.css tests
Remove an empty directory. Returns an error if the directory is not empty.
rmdir empty_dir rmdir project rmdir: failed to remove 'project': Directory not empty
A common pattern in scripts: mkdir -p is safe to use as an idempotent operation because it does not fail if the directory already exists.
mkdir -p /var/log/myapp touch /var/log/myapp/app.log
Notes
mkdir -p is commonly used in scripts to ensure a directory exists before writing to it. Because it does not fail when the directory already exists, it works safely as an idempotent operation. To remove a directory that contains files, use rm -r instead of rmdir.
touch is primarily used for two purposes: creating empty placeholder files, and updating a file's timestamp to signal changes to build systems.
If you find any errors or copyright issues, please contact us.