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

che*_*chi 2 linux bash zsh touch mkdir

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

   newdir(){ # make a new dir and cd into it
        if [ $# != 1 ]; then
            printf "\nUsage: newdir <dir> \n"
        else
            /bin/mkdir -p $1 && cd $1 
        fi
    }
    
    newfile() { # make a new file, open it for editing, here specified where
        if [ -z "$1" ]; 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 "$2" ]; then
            FILENAME="$2"
            DIRNAME="$1"
            if [ -d "$DIRNAME" ]; then
                cd $DIRNAME    
            else
                newdir $DIRNAME
            fi
        else
            FILENAME="$1"
        fi
    
    touch ./"$FILENAME"
    nano ./"$FILENAME"
    }
Run Code Online (Sandbox Code Playgroud)

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

Léa*_*ris 6

没有任何触摸可以创建父目录路径,因此请使用也适用于 zsh 的标准 POSIX-shell 语法编写自己的路径:

#!/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
}
Run Code Online (Sandbox Code Playgroud)