Make parent directories while creating a new file

9,835

Solution 1

AFAIK, there is nothing standard like that, but you can do it your self:

ptouch() {
  for p do
    _dir="$(dirname -- "$p")"
    mkdir -p -- "$_dir" &&
      touch -- "$p"
  done
}

Then you can do:

ptouch /path/to/directory/file1 /path/to/directory/fil2 ...

Solution 2

Some systems have a install command that can be told to create missing path components.

With the GNU implementation of install,

install -DTm644 /dev/null foo/bar/baz

Would create an empty baz regular file with permission 0644 and would create the foo and foo/bar directories if missing (with permission 0755 regardless of the umask).

Share:
9,835

Related videos on Youtube

Mandar Shinde
Author by

Mandar Shinde

Updated on September 18, 2022

Comments

  • Mandar Shinde
    Mandar Shinde almost 2 years

    I am aware of the fact that mkdir -p /path/to/new/directory will create a new directory, along with parent directory (if needed ).

    If I have to create a new file, along with it's parent directories (where some or all of the parent directories are not present), I could use mkdir -p /path/to/directory && touch /path/to/directory/NEWFILE. But, is there any other command to achieve this?

  • Edward Torvalds
    Edward Torvalds over 9 years
    what is dirname on line 3 ?
  • cuonglm
    cuonglm over 9 years
  • mdo123
    mdo123 almost 7 years
    Or with curl ... curl --create-dirs --output /tmp/create/file.txt file:///dev/null
  • pluga
    pluga about 6 years
    how is p being defined in for p do. I would have thought you'd need to use $@ here...
  • cuonglm
    cuonglm about 6 years
    @Jonah for p do is short form of for p in "$@"; do
  • Pryftan
    Pryftan almost 6 years
    It's admittedly been many, many years, but I'm almost certain that that's possible in other implementations of install too (I'm not sure that /dev/null is a good thing to include in your example though ...).
  • Stéphane Chazelas
    Stéphane Chazelas almost 6 years
    @Pryftan, I didn't mean to imply that it wasn't possible with other install implementations, just that that's the syntax to use for GNU install and how it does it. The syntax would be different for FreeBSD install (you'd at least need -d in place of -D and I don't think it's got an equivalent for -T, though that's only a safeguard option). You need a source file. /dev/null is used to create an empty foo/bar/baz.
  • Pryftan
    Pryftan almost 6 years
    @StéphaneChazelas Right. As I noted it had been years :) As for the source file: well to be fair I wasn't truly paying attention to it other than - well you probably know where my mind was maybe even more than me! With your explanation I can see indeed what you're doing; I wasn't even thinking of files actually so that could be part of the problem too. Anyway yes - install is a great option here.