Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One command to create a directory and file inside it linux command

Suppose my current directory is A. I want to create a directory B and a file "myfile.txt" inside B.

How to do that in one command from Terminal?

Edit:

Directory can be nested multiple times. Like I may want to create B/C/D and then "myfile.txt" inside that. I do not also want to repeat the directory part.

Following command will create directory at any level.

mkdir -p B/C/D  

and

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

will create the directory and the file. But I do not want to repeat the directory part after the touch command. Is that possible?

like image 730
chanchal118 Avatar asked Aug 01 '13 06:08

chanchal118


People also ask

How do you create a file and directory in Linux?

The procedure is as follows: Open the terminal application in Linux. The mkdir command is is used to create new directories or folders. Say you need to create a folder name dir1 in Linux, type: mkdir dir1.

What is the command to create a directory in Linux?

mkdir command in Linux allows the user to create directories (also referred to as folders in some operating systems ). This command can create multiple directories at once as well as set the permissions for the directories.

What is the command to create a file directory?

Use the mkdir command to create one or more directories specified by the Directory parameter.


1 Answers

mkdir B && touch B/myfile.txt 

Alternatively, create a function:

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

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

mkfile B/C/D myfile.txt 

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

like image 184
devnull Avatar answered Sep 22 '22 01:09

devnull