Unix - create path of folders and file

后端 未结 11 2015
面向向阳花
面向向阳花 2020-12-22 18:20

I know you can do mkdir to create a directory and touch to create a file, but is there no way to do both operations in one go?

i.e. if I wa

相关标签:
11条回答
  • 2020-12-22 19:02

    no need for if then statements... you can do it on a single line usign ;

    mkdir -p /my/other/path/here;cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
    

    -- or on two lines --

    mkdir -p /my/other/path/here
    cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
    

    -- the -p prevents error returns if the directory already exists (which is what I came here looking for :))

    0 讨论(0)
  • 2020-12-22 19:02

    In the special (but not uncommon) case where you are trying to recreate the same directory hierarchy, cp --parents can be useful.

    For example if /my/long contains the source files, and my/other already exists, you can do this:

    cd /my/long
    cp --parents path/here/thing.txt /my/other
    
    0 讨论(0)
  • 2020-12-22 19:03

    as I saw and test in a unix forum this solves the problem

    ptouch() {
        for p in "$@"; do
            _dir="$(dirname -- "$p")"
            [ -d "$_dir" ] || mkdir -p -- "$_dir"
        touch -- "$p"
        done
    }
    
    0 讨论(0)
  • 2020-12-22 19:12

    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
    
    0 讨论(0)
  • 2020-12-22 19:12

    if you want simple with only 1 param snippet :

    rm -rf /abs/path/to/file;  #prevent cases when old file was a folder
    mkdir -p /abs/path/to/file; #make it fist as a dir
    rm -rf /abs/path/to/file; #remove the leaf of the dir preserving parents 
    touch /abs/path/to/file; #create the actual file
    
    0 讨论(0)
提交回复
热议问题