Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix - create path of folders and file

People also ask

How do I create a directory path in Linux?

The procedure is as follows: Open the terminal application in Linux. The mkdir command is is used to create new directories or folders. Say you need to create a folder name dir1 in Linux, type: mkdir dir1.

How do I create a parent directory in Unix?

A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.


Use && to combine two commands in one shell line:

COMMAND1 && COMMAND2
mkdir -p /my/other/path/here/ && touch /my/other/path/here/cpedthing.txt

Note: Previously I recommended usage of ; to separate the two commands but as pointed out by @trysis it's probably better to use && in most situations because in case COMMAND1 fails COMMAND2 won't be executed either. (Otherwise this might lead to issues you might not have been expecting.)


You need to make all of the parent directories first.

FILE=./base/data/sounds/effects/camera_click.ogg

mkdir -p "$(dirname "$FILE")" && touch "$FILE"

If you want to get creative, you can make a function:

mktouch() {
    if [ $# -lt 1 ]; then
        echo "Missing argument";
        return 1;
    fi

    for f in "$@"; do
        mkdir -p -- "$(dirname -- "$f")"
        touch -- "$f"
    done
}

And then use it like any other command:

mktouch ./base/data/sounds/effects/camera_click.ogg ./some/other/file

Do it with /usr/bin/install:

install -D /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt

when you don't have a source file:

install -D <(echo 1) /my/other/path/here/cpedthing.txt

This is what I would do:

mkdir -p /my/other/path/here && touch $_/cpredthing.txt

Here, the $_ is a variable that represents the last argument to the previous command that we executed in line.

As always if you want to see what the output might be, you can test it by using the echo command, like so:

echo mkdir -p /code/temp/other/path/here && echo touch $_/cpredthing.txt

Which outputs as:

mkdir -p /code/temp/other/path/here
touch /code/temp/other/path/here/cpredthing.txt

As a bonus, you could write multiple files at once using brace expansion, for example:

mkdir -p /code/temp/other/path/here &&
touch $_/{cpredthing.txt,anotherfile,somescript.sh}

Again, totally testable with echo:

mkdir -p /code/temp/other/path/here
touch /code/temp/other/path/here/cpredthing.txt /code/temp/other/path/here/anotherfile /code/temp/other/path/here/somescript.sh

#!/bin/sh
for f in "$@"; do mkdir -p "$(dirname "$f")"; done
touch "$@"

you can do it in two steps:

mkdir -p /my/other/path/here/
touch /my/other/path/here/cpedthing.txt

if [ ! -d /my/other ]
then
   mkdir /my/other/path/here
   cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
fi