One command to create a directory and file inside

2019-02-02 00:09发布

问题:

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?

回答1:

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.



回答2:

For this purpose, you can create your own function. For example:

$ echo 'mkfile() { mkdir -p "$(dirname "$1")" && touch "$1" ;  }' >> ~/.bashrc
$ source ~/.bashrc
$ mkfile ./fldr1/fldr2/file.txt

Explanation:

  • Insert the function to the end of ~/.bashrc file using the echo command
  • The -p flag is for creating the nested folders, such as fldr2
  • Update the ~/.bashrc file with the source command
  • Use the mkfile function to create the file


回答3:

devnull's answer provides a function:

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

This function did not work for me as is (I'm running bash 4.3.48 on WSL Ubuntu), but did work once I removed the double dashes. So, this worked for me:

echo 'mkfile() { mkdir -p "$1" && touch "$1"/"$2" }' >> ~/.bash_profile
source ~/.bash_profile
mkfile sample/dir test.file


回答4:

Just a simple command below is enough.

mkdir a && touch !$/file.txt

Thx



回答5:

This might work:

mkdir {{FOLDER NAME}}
cd {{FOLDER NAME}}
touch {{FOLDER NAME}}/file.txt