Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command to create a new file and its parent directories if necessary

Tags:

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

like image 590
Peng Zhang Avatar asked Jul 10 '14 01:07

Peng Zhang


People also ask

How do I create a parent folder in bash?

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).

How do you create a new file in bash?

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.

How do I create a parent directory?

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.

Which option can be used to create a directory structure with the missing parent directories?

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.


2 Answers

install is your friend:

install -Dv /dev/null some/new/path/base-filename 
like image 68
linuts Avatar answered Sep 30 '22 18:09

linuts


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" 
like image 32
mklement0 Avatar answered Sep 30 '22 19:09

mklement0