Unix - create path of folders and file

后端 未结 11 2014
面向向阳花
面向向阳花 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 18:48

    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.)

    0 讨论(0)
  • 2020-12-22 18:48

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

    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
    
    0 讨论(0)
  • 2020-12-22 18:53
    if [ ! -d /my/other ]
    then
       mkdir /my/other/path/here
       cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
    fi
    
    0 讨论(0)
  • 2020-12-22 19:00
    #!/bin/sh
    for f in "$@"; do mkdir -p "$(dirname "$f")"; done
    touch "$@"
    
    0 讨论(0)
  • 2020-12-22 19:02

    you can do it in two steps:

    mkdir -p /my/other/path/here/
    touch /my/other/path/here/cpedthing.txt
    
    0 讨论(0)
提交回复
热议问题