Benches macOS

2

Touch Create Directory and File?

apple Verified

Imported from the Apple Support Forums via the Wayback Machine 🔗

Does anybody know if there is a way for touch (or any other command) to create a file and if the directory does not exists it will create it?

Thanks.

2 replies

Sign in or join Beachball Help to reply.

  1. 0

    Niel

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    Not automatically. Run mkdir with the p option and without the file's name, and then the other command.

    (51130)

  2. 0

    Nils C. Anderson

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    Here's a crude script. You could probably add a check to test

    whether you have permission to write in the directory where you

    are wanting to create the file.


    !/bin/bash
    BASENAME=/usr/bin/basename
    DIRNAME=/usr/bin/dirname
    MKDIR=/bin/mkdir
    TOUCH=/usr/bin/touch
    DIRECTORY=`${DIRNAME} ${1}`
    FILENAME=`${BASENAME} ${1}`
    if [[ ! -d ${DIRECTORY} ]]
    then
    ${MKDIR} ${DIRECTORY}
    fi
    if [[ ! -f ${FILENAME} ]]
    then
    ${TOUCH} ${DIRECTORY}/${FILENAME}
    fi