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 this:
if (-d '/opt/test') { touch '/opt/test/test.txt'; } else { mkdir -p '/opt/test'; touch '/opt/test/test.txt' }
Is there any better way to simplify the code? I hope there is some system commands that can do the same job with only one line.
touch is not able to create directories, you need mkdir for that. However, mkdir has the useful -p / --parents option which creates a full directory structure. If you think you will need this more often and don't want to type the path twice every time, you can also make a Bash function or a script for it.
We use touch to create plain files, we use mkdir to create directories. This is the difference.
You can create directories one by one with mkdir, but this can be time-consuming. To avoid that, you can run a single mkdir command to create multiple directories at once. To do so, use the curly brackets {} with mkdir and state the directory names, separated by a comma.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With