Search code examples
linuxbashtouchzshmkdir

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


I have the following two functions defined in my .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"
    }

but I am wondering, is there a version of touch that acts similar to mkdir -p, in that it can create parent dirs as needed in one line/command?


Solution

  • There is no touch that can create parent directory path, so write your own in standard POSIX-shell grammar that also works with 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
    }