创建文件及其父目录

我知道touch命令会创建一个文件:

 touch test1.txt 

但我如何创建一个文件及其完整路径?

例如我的桌面什么都没有:

 ~/Desktop/$ ls ~/Desktop/$ 

我想在~/Desktop/a/b/c/d/e/f/g/h/1.txt 。 我可以用一个简单的命令来做到这一点:

 $ touch ~/Desktop/a/b/c/d/e/f/g/h/1.txt 

而不是手动创建完整路径,然后创建文件?

touch无法创建目录,你需要mkdir

但是, mkdir具有有用的-p / --parents选项,可以创建完整的目录结构。

来自man mkdir

  -p, --parents no error if existing, make parent directories as needed 

因此,您在特定情况下需要的命令是:

 mkdir -p ~/Desktop/a/b/c/d/e/f/g/h/ && touch ~/Desktop/a/b/c/d/e/f/g/h/1.txt 

如果您认为自己需要更频繁,并且不想每次都输入两次路径,那么您也可以为它创建一个Bash函数或脚本。

  • Bash函数(将此行附加到~/.bashrc以使其可供您的用户使用,否则当您退出终端时它将再次消失):

     touch2() { mkdir -p "$(dirname "$1")" && touch "$1" ; } 

    它可以像这样简单地使用:

     touch2 ~/Desktop/a/b/c/d/e/f/g/h/1.txt 
  • Bash脚本(使用sudo将其存储在/usr/local/bin/touch2中以使其可供所有用户使用,否则只能在~/bin/touch2供您的用户使用):

     #!/bin/bash mkdir -p "$(dirname "$1")" && touch "$1" 

    不要忘记使用chmod +x /PATH/TO/touch2使脚本可执行。

    之后你也可以像这样运行它:

     touch2 ~/Desktop/a/b/c/d/e/f/g/h/1.txt 

可以使用带-D标志的install命令。

 bash-4.3$ install -D /dev/null mydir/one/two bash-4.3$ tree mydir mydir └── one └── two 1 directory, 1 file bash-4.3$ 

如果我们有多个文件,我们可能要考虑使用项目列表(注意,记得引用带空格的项目),并迭代它们:

 bash-4.3$ for i in mydir/{'subdir one'/{file1,file2},'subdir 2'/{file3,file4}} ; do > install -D /dev/null "$i" > done bash-4.3$ tree mydir mydir ├── one │  └── two ├── subdir 2 │  ├── file3 │  └── file4 └── subdir one ├── file1 └── file2 

或者使用数组:

 bash-4.3$ arr=( mydir/{'subdir one'/{file1,file2},'subdir 2'/{file3,file4}} ) bash-4.3$ for i in "${arr[@]}"; do install -D /dev/null "$i"; done bash-4.3$ tree mydir mydir ├── one │  └── two ├── subdir 2 │  ├── file3 │  └── file4 └── subdir one ├── file1 └── file2 

为此,您可以创建自己的函数,例如:

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

首先,我们使用echo命令将函数插入〜/ .bashrc文件的末尾。 函数中的-p标志允许创建嵌套文件夹,例如我们示例中的fldr2。 最后,我们使用source命令更新文件,最终执行最近创建的mkfile命令