With the -p
(--parents
) option, mkdir
creates parent directories if necessary.
touch
, vim
or >
can create new files in bash, but only when the parent directories exist.
How to create a new file and its parent directories if necessary, in one command? Just like what the -p
does for mkdir
You can go back to the parent directory of any current directory by using the command cd .. , as the full path of the current working directory is understood by Bash . You can also go back to your home directory (e.g. /users/jpalomino ) at any time using the command cd ~ (the character known as the tilde).
To create a new file, run the "cat" command and then use the redirection operator ">" followed by the name of the file. Now you will be prompted to insert data into this newly created file. Type a line and then press "Ctrl+D" to save the file.
A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.
Building a structure with multiple subdirectories using mkdir requires adding the -p option. This makes sure that mkdir adds any missing parent directories in the process.
install is your friend:
install -Dv /dev/null some/new/path/base-filename
Here's a shell function:
mkfileP() { mkdir -p "$(dirname "$1")" || return; touch "$1"; } # Sample call mkfileP "./newSubDir/test.txt" && echo 'created or touched' || echo 'failure'
You can place it in your shell profile, for instance.
Alternatively, implement it as a script (add error handling and command-line help as needed):
#!/usr/bin/env bash mkdir -p "$(dirname "$1")" || exit touch "$1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With