mkdir -p for files

Install will do this, if given the source file /dev/null. The -D argument says to create all the parent directories:

anthony@Zia:~$ install -D /dev/null /tmp/a/b/c
anthony@Zia:~$ ls -l /tmp/a/b/c 
-rwxr-xr-x 1 anthony anthony 0 Jan 30 10:31 /tmp/a/b/c

Not sure if that's a bug or not—its behavior with device files isn't mentioned in the manpage. You could also just give it a blank file (newly created with mktemp, for example) as the source.


No, it does not as far as I know. But you can always use mkdir -p and touch after each other:

f="/a/b/c.txt"
mkdir -p -- "${f%/*}" && touch -- "$f"

I frequently ran into this kind of situation, so I simply wrote a function in my .bashrc file. It looks like this

function create() {
    arg=$1
    num_of_dirs=$(grep -o "/" <<< $arg | wc -l)
    make_dirs=$(echo $arg | cut -d / -f1-$num_of_dirs)
    mkdir -p $make_dirs && touch $arg
}

So, when I want to create a file inside a path of non-existent directories, I will say

create what/is/it  # will create dirs 'what' and 'is', with file 'it' inside 'is'