Creating directories with mkdir
- Version
- unversioned
- Review
- Draft
Summary#
mkdir creates directories. With -p it also creates missing parents and accepts directories that already exist.
Syntax#
mkdir directory
mkdir -p parent/child
mkdir -m 700 private_directory
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
umask 022
mkdir -p -m 700 data/private/keys
mkdir -p data/private/keys
if mkdir data/private 2>/dev/null; then
echo 'created again'
else
echo 'plain mkdir fails: the directory exists'
fi
stat -c '%a %n' data data/private data/private/keys
)
Expected output#
plain mkdir fails: the directory exists
755 data
755 data/private
700 data/private/keys
Common mistakes#
With -p, the -m mode applies only to the directory named on the command line. Newly created parents get their mode from the umask, with owner write and search permission added, so data and data/private above are not 700. Set umask 077 first when every new level must be private.
Version applicability#
This entry describes GNU coreutils mkdir. The stat -c format in the example is also specific to GNU-style stat; BSD and macOS stat use -f.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0