Explore Courses Blog Tutorials Interview Questions
0 votes
in Linux by (18.4k points)
edited by

Imagine my current directory is A. I want to create the directory B and the file named "myfile.txt" inside the directory B.

How to do this in one command using a Terminal?


The directory can be nested multiple times. I would like to create B/C/D and then a file named "myfile.txt" inside that. I don't want to repeat my directory part.

The following command will create a directory at any level.

mkdir -p B/C/D 


mkdir -p B/C/D && touch B/C/D/myfile.txt

This is to create a directory and a file. But I do not want to repeat this directory part after each touch command. Is this possible?

1 Answer

0 votes
by (36.8k points)

Use the below command:

mkdir B && touch B/myfile.txt

Alternatively, create the function:

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

Execute it with two arguments: path to create and  the filename. Saying:

mkfile B/C/D myfile.txt

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

Come and join Linux training to gain great knowledge. 

Do check out the video below

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories