3

I know mkdir -p will make directories recursively.

I know touch will create a file recursively.

I know mkdir -p foo/bar; touch foo/bar/baz.txt will work, but is there a flag or something for touch so I can one-step this?

I'm sure this question has been asked before a million times but for some reason I'm coming up empty.

corysimmons
  • 7,296
  • 4
  • 57
  • 65
  • 1
    there are no options to `touch` that will allow this. However, you can write a shell function that combines the two calls. Good luck. – shellter Feb 20 '16 at 19:43
  • assume that what you are doing is already one step. Otherwise search for "make_path in linux" – Jay Kumar R Feb 20 '16 at 19:53
  • Eh, it's a bummer it's not DRY, but I've lived this long without it. make_path doesn't come with bash and seems more like a Perl function so I'll probably just do without. Thanks everyone. =) – corysimmons Feb 20 '16 at 20:57

3 Answers3

5

what about an alias or a function:

function my_touch {
  mkdir -p $(dirname $1) && touch $1
}

my_touch /tmp/a/b/aaa ; ls -l /tmp/a/b/aaa
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
2
function mytouch { for x in "$@"; do mkdir -p -- `dirname -- "$item"` && touch -- "$x"; done }

usage:

mytouch aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt

$ ls -- aa/bb/cc/dd.txt --a/b/c/d.txt -a/b/c/d.txt                                                    
--a/b/c/d.txt   -a/b/c/d.txt    aa/bb/cc/dd.txt
Wanming Zhang
  • 323
  • 1
  • 8
  • 3
    You're not doing it well here: there are LOTS of quotes missing. Also, this won't work if called as, e.g., `mytouch -hello`. And even when you fix all the quotes, because of `dir=$(dirname "$1")`, you won't be able to have trailing newlines in `dir`, e.g., `mytouch $'a/b/c\n/d`. – gniourf_gniourf Feb 21 '16 at 17:55
  • pluse-uno for "Do one thing and do it well", as it doesn't seem that the O.P. has absorbed a key point of unix/linux philosophy, but I think gniourf_gniourf has some valid comments. Good luck to all. – shellter Feb 22 '16 at 16:17
2

The GNU implementation of install can do this:

install -D /dev/null foo/bar/baz.txt
# will create an empty baz.txt file in foo/bar

If you're using OS X without coreutils you have to use functions, like already suggested

hgiesel
  • 5,430
  • 2
  • 29
  • 56
  • Good alternative. Can you check if will pass the `mytouch $'a/b/c\n/d` test in @gniourf_gniourf 's comment above. Good luck to all. – shellter Feb 22 '16 at 16:15