1

Is there any single command to create a file with missing directory structure?

Suppose I have a variable LOG_STORAGE_PATH=/var/log/app-log/access.log in my shell script and I dont know if app-log directory and access.log file is present.

Is there a single command, like mkdir -p </some/random/path> which creates all intermediate directories if not present, to create a file with missing directories in between.

This would have been accomplished with the help of

LOG_STORAGE_PATH=/var/log/app-log/
ACCESS_LOG_FILE=access.log
ACCESS_LOG_FILE_PATH=${LOG_STORAGE_PATH}/${ACCESS_LOG_FILE}
if [ ! -d ${LOG_STORAGE_PATH} ]
then
    mkdir -p ${LOG_STORAGE_PATH}
fi  
if [ ! -f ${ACCESS_LOG_FILE_PATH} ]
then
    touch ${ACCESS_LOG_FILE_PATH}
fi

I was looking for touch command with same functionality as mkdir -p, but its not present.

It would have been very useful if we had a touch -p /var/log/app-log/access.log command which can create a file along with missing directories, or if directories are present then just create the file or even if directories and file both present then just update the access time of the file.

Just for a thought, maybe we wouldn't have to use if [ ! -f <some file> ] or if [ ! -d <some dir path> ] in our scripts, we could have directly used touch -p ${ACCESS_LOG_FILE_PATH}

Mahesh Jadhav
  • 89
  • 1
  • 12
  • 1
    Possible duplicate of [Unix - create path of folders and file](http://stackoverflow.com/questions/9452935/unix-create-path-of-folders-and-file) – piyushj May 18 '16 at 11:28
  • You don't need to test with `-d` and `-f`. Just use `mkdir -p` and `touch`. – user1934428 May 18 '16 at 12:11

1 Answers1

1

You cannot able to do this with single command in unix. To do this you need two commands (mkdir and touch).