How to create a new file via touch if it is in a directory which doesn't exist?

Solution 1:

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)

Explanation:

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

Solution 2:

I would recommend use the &&.

Example:

mkdir ~/this_dir && touch ~/this_dir/new.txt

The && deals accepts a new command. So mkdir this_dir, also do the rest.

This is very useful because can be used for everything, not only for new folders.

Solution 3:

Simple solution, given $file as a file, this should work:

mkdir -p $(dirname $file) && touch $file

or even

# create function
touchfile () {
    local file="$1"
    mkdir -p -- "$(dirname -- "$file")" &&
        touch -- "$file"
}

# then just
touchfile /path/to/file/to/touch/woah