TransWikia.com

Zsh: How to create a directory and file inside it with one command?

Unix & Linux Asked on December 26, 2021

I am curious whether it is possible to create a directory and file inside this directory with one command, similar to mkdir -p but for a text file and intermediate directory.

I read through the touch manual and found nothing.
Neither I could find the answer on unix stackexchange.

Is there any way to do so (perhaps without using other command rather than touch), since it is pretty routine task to initiate a new directory with a file?

One Answer

There's the install command from GNU coreutils with the -D option which can copy a file and create the directories leading to them in one go (and also let you specify the ownership and permissions). By default, it creates executable files and doesn't honour the umask as it's typically used as a dev tool in make install stages.

install -m u=rw,go=r -D /dev/null some/new/file

(the permissions of the directory components it creates are always u=rwx,go=rx).

Or you could always implement it as a create Zsh function such as:

create() {
  local file ret=0
  for file do
    mkdir -p -- "$file:h" && true >> "$file" || ret=$?
  done
  return "$ret"
}

Though creating an empty regular file seems a bit pointless to me.

Generally, you'd do:

mkdir -p some/dir
your-editor some/dir/some-file

To create some-file (the file would be created as soon you save it (with actual content) in your editor).

Or any other command that creates some content like:

some-command > some/dir/some-file
wget -o some/dir/some-file https://example.com/whatever
cp source some/dir/some-file
...etc.

Answered by Stéphane Chazelas on December 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP