Bash command to create a new file and its parent directories if necessary

Here's a shell function:

mkfileP() { mkdir -p "$(dirname "$1")" || return; touch "$1"; }

# Sample call
mkfileP "./newSubDir/test.txt" && echo 'created or touched' || echo 'failure'

You can place it in your shell profile, for instance.

Alternatively, implement it as a script (add error handling and command-line help as needed):

#!/usr/bin/env bash

mkdir -p "$(dirname "$1")" || exit
touch "$1"

install is your friend:

install -Dv /dev/null some/new/path/base-filename

Tags:

Shell

Bash