Home > Software engineering >  is there a touch that can create parent directories like mkdir -p?
is there a touch that can create parent directories like mkdir -p?

Time:01-16

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?

CodePudding user response:

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
    # Creates leading directories if not exists
    mkdir -p "${arg%/*}"

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

CodePudding user response:

With zsh you can do:

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

mkdir is given the "head" of each argument to make the directories (man zshexpn says the :h expansion modifier works like the dirname tool). Then, assuming you have not unset the MUTLIOS option, the output of : (a command that produces no output) is appended to the files.

  •  Tags:  
  • Related