I need to touch a file with an absolute file name such as: /opt/test/test.txt, but I\'m not sure if there is /opt/test existed on the system. So the code should similar with thi
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.
I defined a touchp
in my ~/.bash_aliases
:
function touchp() {
/bin/mkdir -p "$(dirname "$1")/" && /usr/bin/touch "$1"
}
It silently creates the structure above the file if not present, and is perfectly safe to use when passed a single filename without any directory in front of it.
Perl from command line,
perl -MFile::Basename -MFile::Path=make_path -e'
make_path(dirname($_)), open(F, ">>", $_) for pop;
' /opt/test/test.txt
Bring Python to 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 text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.
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 either the test
or the mkdir
command fail, no touch
command is invoked.