How to touch a file and mkdir if needed in one line

In perl, using one of my favorite module: Path::Tiny.

path("/opt/test/test.txt")->touchpath;

From the doc:

Combines mkpath and touch. Creates the parent directory if it doesn't exist, before touching the file.


I like typing very little, so I put this command into a named fn in my .profile, but I used this formulation for years before I did it:

mkdir -p dirname/sub/dir && touch $_/filename.ext

The variable $_ stores the last argument to the previous command. Pretty handy to know about overall.


mkdir B && touch B/myfile.txt

Alternatively, create a function:

   mkfile() { 
    mkdir -p $( dirname "$1") && touch "$1" 
   }

Execute it with 1 arguments: filepath. Saying:

mkfile B/C/D/myfile.txt

would create the file myfile.txt in the directory B/C/D.


In a shell script, you can simply do:

mkdir -p /opt/test && touch /opt/test/test.txt

mkdir -p will not fail (and won't do anything) if the directory already exists.

In perl, use make_path from the File::Path module, then create the file however you want. make_path also doesn't do anything if the directory exists already, so no need to check yourself.

Tags:

Linux

Perl