Ubuntu – How to create a new file via touch if it is in a directory which doesn’t exist

command line

Let's say the directory ~/this_dir doesn't exist.

I need to be able to run touch ~/this_dir/new.txt to create new.txt in ~/this_dir.

Is there a simple way to make touch also create the directory?

Or an alternative command which would achieve the same thing?


Best Answer

There is the command install which will accomplish what you are asking for.

install -Dv /dev/null this_dir/new.txt

(source: Bash command to create a new file and its parent directories if necessary)


  • install is used to copy files and set attributes (see man install)
  • -D tells the command to "create all leading components of DEST except the last, or all components of --target-directory, then copy SOURCE to DEST"
  • -v causes to show every creation step (can be omitted of course)
  • /dev/null is the source, from where to copy
  • this_dir/new.txt is the target of the copy operation.

@rchard2scout has thankfully pointed out that

The install command is part of GNU Coreutils, which has been marked as "Essential". That means it'll basically always be available.