How to touch a file and mkdir, if necessary, in one line

I need to touch a file with an absolute file name, for example: /opt/test/test.txt, but I'm not sure if / opt / test exists on the system. So the code should be similar to this:

if (-d '/opt/test') { touch '/opt/test/test.txt'; } else { mkdir -p '/opt/test'; touch '/opt/test/test.txt' } 

Is there a better way to simplify the code? I hope that there are some system commands that can do the same job with only one line.

+10
source share
8 answers

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

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

From the doc:

Combines mkpath and touch. Creates a parent directory if it does not exist before touching the file.

+10
source

In a shell script, you can simply:

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

mkdir -p will not work (and will not do anything) if the directory already exists.

In perl, use make_path from the File::Path module, then create the file make_path you want. make_path also does nothing if the directory already exists, so you don't need to check yourself.

+10
source

Perl from the command line

 perl -MFile::Basename -MFile::Path=make_path -e' make_path(dirname($_)), open(F, ">>", $_) for pop; ' /opt/test/test.txt 
+4
source
 mkdir B && touch B/myfile.txt 

Alternatively, create a function:

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

Run it with 1 argument: file path. Saying:

 mkfile B/C/D/myfile.txt 

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

+4
source

I defined a touchp in my ~/.bash_aliases :

 function touchp() { /bin/mkdir -p "$(dirname "$1")/" && /usr/bin/touch "$1" } 

It silently creates a structure over a file if it is missing, and is completely safe to use when transferring a single file name without any directory in front of it.

+2
source

I like to print very little, so I put this command in the name fn in my .profile, but I used this wording for many years before I did this:

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

The $_ variable holds the last argument of the previous command. It’s pretty convenient to know about the general.

+2
source

Connect Python to the command line.

i.e. Use pyp

  cat filepaths.txt | pyp "'mkdir -p '+s[0:-1]|s+'; touch '+o" | sh 

The Pyed Piper ", or pyp, is a linux command line command-line tool like awk or sed, but which uses standard python string and list methods, as well as custom functions designed to quickly get results in an intensive production environment.

0
source

I have this shell function in my .zshalias file:

 function touch-safe { for f in " $@ "; do [ -d $f:h ] || mkdir -p $f:h && command touch $f done } alias touch=touch-safe 

If test or the mkdir command is not mkdir , no touch command is invoked.

0
source

Source: https://habr.com/ru/post/981918/


All Articles