Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 685
cartman Avatar asked Feb 03 '15 10:02

cartman


People also ask

Can you create a directory with touch?

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.

What is difference between touch and mkdir?

We use touch to create plain files, we use mkdir to create directories. This is the difference.

How do I make multiple folders in one mkdir command?

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.


1 Answers

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.

like image 123
Sridhar Nagarajan Avatar answered Oct 23 '22 06:10

Sridhar Nagarajan