6

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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Mandar Shinde
  • 3,156
  • 11
  • 39
  • 58

2 Answers2

6

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 ...
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
cuonglm
  • 150,973
  • 38
  • 327
  • 406
4

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

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • Or with curl ... curl --create-dirs --output /tmp/create/file.txt file:///dev/null – mdo123 Jul 12 '17 at 23:24
  • 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 ...). – Pryftan Aug 10 '18 at 22:39
  • @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`. – Stéphane Chazelas Aug 11 '18 at 09:01
  • @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. – Pryftan Aug 11 '18 at 21:31