有没有可以创建像 mkdir -p 这样的父目录的方法?

is there a touch that can create parent directories like mkdir -p?

我在 .zshrc 中定义了以下两个函数

   newdir(){ # make a new dir and cd into it
        if [ $# != 1 ]; then
            printf "\nUsage: newdir <dir> \n"
        else
            /bin/mkdir -p  && cd  
        fi
    }
    
    newfile() { # make a new file, open it for editing, here specified where
        if [ -z "" ]; then
            printf "\nUsage: newfile FILENAME \n" 
            printf "touches a new file in the current working directory and opens with nano to edit \n\n"
            printf "Alternate usage: newfile /path/to/file FILENAME \n"
            printf "touches a new file in the specified directory, creating the diretory if needed, and opens to edit with nano \n"
        elif [ -n "" ]; then
            FILENAME=""
            DIRNAME=""
            if [ -d "$DIRNAME" ]; then
                cd $DIRNAME    
            else
                newdir $DIRNAME
            fi
        else
            FILENAME=""
        fi
    
    touch ./"$FILENAME"
    nano ./"$FILENAME"
    }

但我想知道,是否有一个类似于 mkdir -p 的 touch 版本,它可以根据需要在一个 line/command 中创建父目录?

没有可以创建父目录路径的方法,所以用标准的 POSIX-shell 语法编写自己的也适用于 zsh:

#!/usr/bin/env sh

touchp() {
  for arg
  do
    # Get base directory
    baseDir=${arg%/*}

    # If whole path is not equal to the baseDire (sole element)
    # AND baseDir is not a directory (or does not exist)
    if ! { [ "$arg" = "$baseDir" ] || [ -d "$baseDir" ];}; then
      # Creates leading directories
      mkdir -p "${arg%/*}"
    fi

    # Touch file in-place without cd into dir
    touch "$arg"
  done
}

使用 zsh 你可以:

mkdir -p -- $@:h && : >>| $@

mkdir 被赋予每个参数的“头”以创建目录(man zshexpn 表示 :h 扩展修饰符的工作方式类似于 dirname 工具)。然后,假设您没有取消设置 MUTLIOS 选项,:(不产生输出的命令)的输出将附加到文件。