Hubbry Logo
MkdirMkdirMain
Open search
Mkdir
Community hub
Mkdir
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Mkdir
Mkdir
from Wikipedia
mkdir
DevelopersVarious open-source and commercial developers
Operating systemUnix, Unix-like, Plan 9, Inferno, DOS, MSX-DOS, FlexOS, OS/2, Windows, ReactOS, KolibriOS
PlatformCross-platform
TypeCommand
LicenseGNU coreutils: GPLv3+
MS-DOS, Plan 9: MIT
FreeDOS: GPLv2+
ReactOS: GPLv2

The mkdir (make directory) command in the Unix, DOS, DR FlexOS,[1] IBM OS/2,[2] Microsoft Windows, and ReactOS[3] operating systems is used to make a new directory. It is also available in the EFI shell[4] and in the PHP scripting language. In DOS, OS/2, Windows and ReactOS, the command is often abbreviated to md.

The command is analogous to the Stratus OpenVOS create_dir command.[5] MetaComCo TRIPOS and AmigaDOS provide a similar MakeDir command to create new directories.[6][7] The numerical computing environments MATLAB and GNU Octave include an mkdir function with similar functionality.[8][9]

History

[edit]

In early versions of Unix (4.1BSD and early versions of System V), this command had to be setuid root as the kernel did not have an mkdir syscall. Instead, it made the directory with mknod and linked in the . and .. directory entries manually. The command is available in MS-DOS versions 2 and later.[10] Digital Research DR DOS 6.0[11] and Datalight ROM-DOS[12] also include an implementation of the md and mkdir commands.

The version of mkdir bundled in GNU coreutils was written by David MacKenzie.[13] It is also available in the open source MS-DOS emulator DOSBox and in KolibriOS.[14]

Usage

[edit]
The ReactOS mkdir command

Normal usage is as straightforward as follows:

mkdir name_of_directory

where name_of_directory is the name of the directory one wants to create. When typed as above (i.e. normal usage), the new directory would be created within the current directory. On Unix and Windows (with Command extensions enabled,[15] the default[16]), multiple directories can be specified, and mkdir will try to create all of them.

Options

[edit]

On Unix-like operating systems, mkdir takes options. The options are:

  • -p (--parents): parents or path, will also create all directories leading up to the given directory that do not exist already. For example, mkdir -p a/b will create directory a if it doesn't exist, then will create directory b inside directory a. If the given directory already exists, ignore the error.
  • -m (--mode): mode, specify the octal permissions of directories created by mkdir .

-p is most often used when using mkdir to build up complex directory hierarchies, in case a necessary directory is missing or already there. -m is commonly used to lock down temporary directories used by shell scripts.

Examples

[edit]

An example of -p in action is:

mkdir -p /tmp/a/b/c

If /tmp/a exists but /tmp/a/b does not, mkdir will create /tmp/a/b before creating /tmp/a/b/c.

And an even more powerful command, creating a full tree at once (this however is a Shell extension, nothing mkdir does itself):

mkdir -p tmpdir/{trunk/sources/{includes,docs},branches,tags}

If one is using variables with mkdir in a bash script, POSIX `special' built-in command 'eval' would serve its purpose.

DOMAIN_NAME=includes,docs
eval "mkdir -p tmpdir/{trunk/sources/{${DOMAIN_NAME}},branches,tags}"

This will create:

          tmpdir
    ________|______
   |        |      |
branches   tags  trunk
                   |
                 sources
               ____|_____
              |          |
          includes     docs

See also

[edit]

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
mkdir, short for "make directory," is a standard command-line utility in Unix-like operating systems that creates one or more new directories specified by the user, initializing their permissions based on the system's default mode modified by the umask. The utility processes directory operands in the order provided, requiring write permission in the parent directory for each creation, and it exits with a status of 0 on success or greater than 0 on failure. The mkdir command first appeared in AT&T UNIX in the early 1970s, establishing it as one of the foundational tools for management in Unix environments. It has since been standardized across POSIX-compliant systems, with the specification defined in IEEE Std 1003.1-2017 (POSIX.1-2017), ensuring portability and consistent behavior on modern platforms such as , BSD variants, and macOS. In addition to the utility, mkdir refers to the underlying (mkdir(2) or mkdir(3)) that kernel-level implementations use to create directories atomically, setting initial permissions from a provided mode argument while respecting the process's . These features make mkdir essential for scripting and in file organization tasks. Equivalents exist in other operating systems, such as the command in DOS and Windows command prompt, though with differing syntax and capabilities.

Introduction

Purpose and Functionality

The mkdir command is a standard command-line utility in operating systems designed to create new directories, also known as folders, within a 's hierarchical . This tool enables users and programs to establish organized containers for storing files and further subdirectories, forming the backbone of navigation and management. Directories play a crucial role in maintaining order in file systems by arranging data in a tree-like , which avoids the disorganization and inefficiency of a flat structure where all files reside at the same level without categorization. This hierarchical approach facilitates logical grouping, easier retrieval, and scalable storage as systems grow, with the serving as the top-level node from which all others branch. In operation, mkdir generates empty directories by default, containing only the standard . (current directory) and .. (parent directory) entries, and supports creating one or more such directories in a single command invocation based on the provided operands. The command interprets directory paths relative to the current when relative paths are used, or from the when absolute paths are specified, allowing flexible placement within the existing hierarchy without altering the working directory itself.

Basic Syntax

The basic syntax of the mkdir command follows the form mkdir [options] dir..., where dir... denotes one or more operands specifying the pathnames of the directories to create, processed in the order provided. These positional arguments consist of directory paths, which may be expressed as relative paths (e.g., subdir) or absolute paths (e.g., /home/user/newdir) using the forward slash (/) as the directory separator in POSIX-compliant systems. If multiple directory paths are supplied, the command attempts to create each one sequentially. The command requires that all components of the specified path except the final directory name already exist; otherwise, it fails with an error indicating the missing parent directory. Additionally, if a target directory already exists, mkdir without options reports an error and does not proceed with creation for that path. In the absence of options enabling recursive behavior, the command is limited to creating only the specified leaf directories and cannot automatically generate intermediate directories along the path.

Historical Development

Origins in Early Unix

The mkdir command originated at Bell Labs during the development of the early Unix operating system in the late 1960s and early 1970s, primarily through the efforts of Ken Thompson and Dennis Ritchie. Unix's file system, influenced by the hierarchical structure of Multics—a project from which Thompson had withdrawn in 1969—evolved to support organized storage beyond flat file arrangements. Initial Unix implementations on the PDP-7 in 1969 featured directories as special files containing name-to-inode mappings, but lacked dynamic creation capabilities, requiring directories to be statically defined during file system initialization with tools like mkfs. By 1971, with the transition to the PDP-11 and the release of Unix Version 1, Thompson and Ritchie introduced support for hierarchical directories with full path names, addressing the limitations of earlier flat or graph-like structures and enabling more flexible organization of files and subdirectories. The mkdir command emerged as a key utility to facilitate this hierarchical model, allowing users to dynamically create directories at runtime rather than relying solely on system bootstrapping. In Unix Version 1, documented in the first edition of the Unix Programmer's Manual dated November 3, 1971, mkdir was implemented as a user-level command owned by Thompson (ken) and Ritchie (dmr), written in for the PDP-11. Its basic syntax, mkdir dirname, created a new directory with the specified name, automatically populating it with the standard entries "." (referencing itself) and ".." (referencing the parent directory), and assigned ownership to the system's user ID without permission checks—a noted bug in the initial design. This functionality was essential for building tree-like file systems, replacing the more rigid approaches of prior systems and laying the groundwork for Unix's enduring emphasis on modularity and user control. Over the subsequent years from 1972 to 1979, spanning Unix Versions 2 through 6, mkdir was refined alongside the system's growth, integrating with the evolving shell environment—initially Thompson's simple sh and later enhancements—while the core Unix kernel was rewritten in C by Ritchie starting in 1973 for Version 3. These early versions, distributed internally at Bell Labs and to select academic institutions, established mkdir as a foundational tool for file system management, with its presence confirmed in the Second Edition manual of June 1972, where it retained core functionality for creating one or more specified directories in mode 17. The command's design prioritized simplicity and portability, reflecting Unix's philosophy of small, composable utilities that supported multi-user environments without excessive complexity.

Standardization and Evolution

The mkdir command was included in the inaugural .1-1988 standard (IEEE Std 1003.1-1988), which mandated its core functionality for creating one or more directories specified by path operands, initializing permissions from an optional -m mode argument modified by the process , and reporting errors such as EEXIST for preexisting directories or EPERM for insufficient privileges. Evolution in Unix variants introduced key enhancements beyond the baseline. In BSD, the -p option—allowing recursive creation of parent directories without error if intermediates already exist—was added in 4.3BSD, released in 1986, to simplify nested directory construction. Coreutils further extended mkdir in the 1990s with the -v (verbose) option, which prints a message for each successfully created directory, aiding in scripting and debugging. Later POSIX revisions refined path handling and error conditions. .1-2001 (ISO/IEC 9945:2001) updated the specification to clarify behavior with symbolic links in paths, mandating failure with ELOOP if more than {SYMLOOP_MAX} (at least 40) symbolic links are encountered during resolution, while ensuring the final path component is a directory entry. Modern systems extend support for large paths beyond the POSIX minimum {PATH_MAX} of at least 256 bytes, with implementations like allowing up to 4096 bytes via kernel extensions for variable-length paths. Early Unix implementations featured non-standard behaviors that were later deprecated. In Version 7 Unix (), mkdir lacked the -m option for explicit mode setting, defaulting to permissions derived solely from (typically 0777 masked), and required setuid-root privileges because the kernel disallowed non-root directory creation; these were replaced by POSIX.1-1988's standardized -m option and kernel modifications enabling unprivileged operation.

Command Usage

General Arguments

The mkdir utility accepts one or more positional arguments, each consisting of a pathname specifying the directory to be created. These pathnames must be valid relative or absolute paths within the , and the utility processes them in the order specified on the command line. In environments where the shell supports pathname expansion, wildcards such as * can be used to generate multiple positional arguments indirectly; for instance, a pattern like dir* expands to matching directory names before mkdir receives them, allowing batch creation based on existing patterns. When multiple positional arguments are provided, mkdir attempts to create each directory sequentially, proceeding to the next even if a prior attempt fails. This behavior ensures partial success where possible, such as when permission is denied for one path but granted for others; however, the overall reflects any failures encountered. For example, if a user lacks write privileges in a target location, the halts creation for that specific path but continues with subsequent ones. Error handling in mkdir includes diagnostic messages printed to for issues like attempting to create a directory that already exists, typically reporting "File exists" in such cases. The is 0 if all specified directories are created successfully, and greater than 0 (commonly 1) if any error occurs during processing. These mechanisms allow scripts and users to detect and respond to failures programmatically. Positional arguments must adhere to file system constraints, including limits on pathname length; in many systems such as , the maximum is 4096 bytes (where PATH_MAX is defined as 4096), though requires support for at least 256 bytes. Exceeding this limit results in an error, such as "File name too long," preventing directory creation regardless of permissions.

Key Options

The mkdir command supports several key options that enhance its functionality for creating directories, allowing users to handle directories, set permissions, and provide output feedback. The -p option, which creates directories as needed and does not generate an error if the target directory already exists, was introduced in System V to address limitations in early Unix versions where nested path creation required manual intervention. This option is particularly useful for scripting and , preventing failures in hierarchical structures. Another common option is -m, which sets the permissions of the newly created directory according to the specified mode, such as -m 755 for owner read/write/execute and group/others read/execute. This allows immediate configuration of access rights upon creation, overriding default settings for the directory. The -v or --verbose provides detailed output, printing a for each directory created, which aids in monitoring operations in logs or interactive sessions. For more advanced usage, implementations include --parents as an alias for -p, --mode=MODE for explicit permission setting (equivalent to -m), --help to display usage information, and --version to show the program's version details. These long-form options follow standards for consistency across utilities. When combining options, such as mkdir -p -m 700 /path/to/dir, the -p ensures parent directories are created with default permissions before applying the -m mode to the final target, establishing a precedence where mode settings occur post-creation. This combination is essential for secure, nested directory setups in environments like system administration.

Usage Examples

The mkdir command is commonly used to create a single directory in the current . For example, executing mkdir newdir will create a directory named "newdir" if it does not already exist; if the directory already exists, the command reports an error and exits with a nonzero status. To create multiple directories simultaneously, the command accepts multiple operands. For instance, mkdir dir1 dir2 dir3 creates three separate directories named "dir1", "dir2", and "dir3" in the current directory, succeeding only if none exist or handling partial failures by creating those that are possible. The -p option enables the creation of parent directories as needed without error if intermediates already exist. An example is mkdir -p /home/user/docs/projects, which creates the full path "/home/user/docs/projects", making "docs" and its parent if absent, while treating existing directories silently. For setting permissions and verbosity, options like -m and -v can be combined with shell chaining. The command mkdir -m 700 secret && mkdir -v public first creates a private directory "secret" with owner-only permissions ( octal mode) and then creates "" while printing a confirmation message for the latter. In shell scripting, mkdir integrates with commands like date for dynamic paths. For example, mkdir -p "$(date +%Y/%m/%d)" creates a nested directory structure based on the current date, such as "2025/11/10", ensuring parents are made if needed.

System Variations

POSIX Specifications

The POSIX.1-2017 standard (IEEE Std 1003.1-2017) specifies the mkdir utility as a required command for creating one or more directories, with its behavior defined in terms of the underlying mkdir() system function. The basic synopsis is mkdir [-p] [-m mode] dir..., where dir represents the pathname(s) of the directory or directories to create, and the utility must support multiple operands up to the system's {PATH_MAX} limit for each path. For each dir operand, mkdir performs actions equivalent to the mkdir() function, invoked with a mode argument derived from the default value of S_IRWXU|S_IRWXG|S_IRWXO (rwxrwxrwx in octal notation 0777), modified by the process's file mode creation mask (umask). The -m mode option, which is optional but part of the standard synopsis, allows the user to set the file permission bits of the new directory explicitly, accepting either octal numbers or symbolic modes relative to the default a=rwx permissions, with the resulting mode still adjusted by the umask. The -p option, also optional and not required for conformance but commonly implemented, enables the creation of any missing intermediate pathname components in the specified paths, using the mode (S_IWUSR|S_IXUSR|~filemask)&0777 (ensuring owner write and execute permissions adjusted by umask) for those intermediates and ignoring existing directories without error. No verbose output option is mandated by the standard, though implementations may provide extensions for it. Upon successful creation of all specified directories (or if -p is used and they already exist), mkdir shall exit with a status of 0; otherwise, it shall exit with a status greater than 0 and write a diagnostic message to standard error describing the failure for the first unsuccessful operand. Required error conditions mirror those of the mkdir() function, including [EEXIST] if the directory already exists (unless -p is specified) and [ENOENT] if a component of the path prefix does not exist or the path is empty (mitigated by -p for intermediates). Additional mandated diagnostics cover cases such as [EACCES] for permission denials, [ENOSPC] for insufficient space, and [ENAMETOOLONG] if a pathname exceeds {PATH_MAX} or a component exceeds {NAME_MAX}. The utility's integration with other POSIX utilities, such as using ls to verify directory creation post-execution, aligns with standard shell practices but is not directly specified in the mkdir requirements.

Implementation Differences

In Unix-like systems such as , coreutils implementation of mkdir offers an extensive set of options, including --parents (-p) to create intermediate directories, --mode (-m) to set permissions explicitly, --verbose (-v) to display , and --context (-Z) for SELinux security contexts. This version handles paths that traverse symbolic links by following them to the target, ensuring directories are created in the resolved location unless otherwise specified. On Windows, the Command Prompt's md (or mkdir) command serves as the equivalent, creating directories and subdirectories with support for intermediate paths when command extensions are enabled (the default behavior since Windows XP). Unlike Unix variants, it uses forward slashes (/) or backslashes () interchangeably for paths but lacks explicit options like -p or -m; instead, it implicitly creates nested structures in a single invocation, such as md \path\to\dir. Permissions are determined by inheriting the parent directory's access control lists (ACLs) or applying system defaults, as Windows does not implement umask and ignores any Unix-style mode specifications. In PowerShell, the New-Item cmdlet with -ItemType Directory provides a more flexible alias, supporting parameters for paths and attributes but still relying on ACL inheritance for access control. macOS, derived from BSD Unix, employs a mkdir implementation closely aligned with standards, featuring options like -p for recursive creation, -m for mode setting, and -v for verbosity. However, it imposes stricter filesystem constraints compared to many distributions, including a practical path length limit of around characters (enforced by the HFS+ and APFS filesystems), beyond which directory creation fails even with valid permissions. FreeBSD's mkdir shares these core options (-p, -m, -v) but adheres to similar path handling without additional extensions for links beyond standard resolution. In legacy systems like , the md command is rudimentary, creating only single-level directories without support for , explicit permissions, or path separators beyond basic drive letters and backslashes (e.g., md c:\dir). It operates without mode controls, defaulting to basic (FAT) attributes inherited from the volume. For cross-platform compatibility in modern applications, Python's os.mkdir function provides a programmatic alternative, creating a single directory while respecting the umask and specified mode on systems but ignoring mode on Windows in favor of default ACLs.

Advanced Applications

Permissions and Security

When creating a directory using mkdir, the default permissions are set to 0777 (read, write, and execute for owner, group, and others) minus the current process's value, ensuring that the resulting permissions reflect the system's for new files and directories. This mechanism, inherited from early systems, prevents overly permissive access by default while allowing customization. The -m (or --mode) option overrides this default, enabling explicit specification of permissions such as owner, group, read, write, and execute bits; for instance, using 0700 creates a private directory accessible only by the owner, which is essential for protecting sensitive data. Security risks arise primarily from race conditions during directory creation, particularly in non-atomic operations where an attacker could exploit the time between checking for a directory's and creating it, leading to time-of-check-to-time-of-use (TOCTOU) vulnerabilities. Without the -p option, mkdir fails if parent directories do not exist, but in scripted or multi-step scenarios, this can expose systems to symlink attacks in shared or world-writable locations like /tmp, where an adversary might replace the target with a malicious link before creation completes. The -p option mitigates this by creating intermediate directories as needed, reducing the window for interference, though it does not eliminate all TOCTOU risks in concurrent environments. World-writable directories amplify these threats, as they allow unauthorized modifications that could redirect operations to sensitive areas, potentially enabling or data tampering. In multi-user environments, best practices emphasize using the -m option to enforce restricted access from the outset, such as 0755 for shared read-execute access or 0700 for isolation, thereby minimizing exposure to unauthorized users. Regular auditing of directory permissions is crucial, especially on shared systems, to detect and correct overly permissive settings that could facilitate attacks. In security-enhanced environments like those using SELinux, mkdir respects and inherits security contexts from the parent directory or process, labeling the new directory with appropriate types (e.g., user_home_t) to enforce mandatory access controls without additional intervention. Similar inheritance applies in AppArmor-configured systems, where profile policies constrain the creating process's ability to set permissive modes, aligning with path-based confinement rules.

Integration in Scripting

The mkdir command is frequently integrated into shell scripts to automate directory creation, ensuring paths exist before performing file operations or deployments. A common pattern involves conditional checks to avoid errors when a directory already exists, such as using the test utility to verify directory presence before invoking mkdir. For instance, the construct [ -d "$dir" ] || mkdir -p "$dir" creates the directory only if it does not exist, leveraging the -p option to handle parent directories without failing on existing ones. This approach is portable across -compliant shells like sh, where test returns a zero for existing directories and mkdir -p succeeds silently if the target already exists. In scenarios, mkdir supports tasks like generating dated directories for . For example, backup scripts often create paths like /backup/$(date +%Y-%m-%d) to organize incremental or full archives by date, ensuring structured storage without manual intervention. Similarly, deployment tools such as employ equivalents to mkdir via the file module with state: directory, which creates paths like /etc/app/config if absent, including intermediates, to prepare environments idempotently across hosts. Error handling in scripts typically involves capturing mkdir's , which is zero on success (including when -p skips existing directories) and nonzero on failure, such as permission denials. Scripts can check this with $? immediately after execution, e.g., mkdir -p "$dir" || { echo "Failed to create $dir" >&2; exit 1; }, to halt or log issues. For auditing, the GNU-specific -v option prints messages for each created directory to , enabling verbose in scripts like mkdir -pv "$dir" 2>> script.log, which aids without altering core functionality. In advanced Bash or Zsh scripting, mkdir -p integrates seamlessly with loops for dynamic path creation, such as for subdir in alpha beta; do mkdir -p "/base/$subdir"; done, allowing scalable handling of variable structures. This pattern maintains cross-shell portability when restricted to POSIX sh features, avoiding Bash-specific extensions like brace expansion.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.