Make parent directories while creating a new file
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).
Related videos on Youtube
Mandar Shinde
Updated on September 18, 2022Comments
-
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 over 9 yearswhat is dirname on line 3 ?
-
cuonglm over 9 years@edwardtorvalds: see pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html
-
mdo123 almost 7 yearsOr with curl ... curl --create-dirs --output /tmp/create/file.txt file:///dev/null
-
pluga about 6 yearshow is
p
being defined infor p do
. I would have thought you'd need to use$@
here... -
cuonglm about 6 years@Jonah
for p do
is short form offor p in "$@"; do
-
Pryftan almost 6 yearsIt'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 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 GNUinstall
and how it does it. The syntax would be different for FreeBSDinstall
(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 emptyfoo/bar/baz
. -
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.