One command to create a directory and file inside it linux command

前端 未结 9 1204
無奈伤痛
無奈伤痛 2020-12-24 12:39

Suppose my current directory is A. I want to create a directory B and a file \"myfile.txt\" inside B.

How to do th

相关标签:
9条回答
  • 2020-12-24 12:53
    mkdir -p Python/Beginner/CH01 && touch $_/hello_world.py
    

    Explanation: -p -> use -p if you wanna create parent and child directories $_ -> use it for current directory we work with it inline

    0 讨论(0)
  • 2020-12-24 12:59

    devnull's answer provides a function:

    mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }
    

    This function did not work for me as is (I'm running bash 4.3.48 on WSL Ubuntu), but did work once I removed the double dashes. So, this worked for me:

    echo 'mkfile() { mkdir -p "$1" && touch "$1"/"$2" }' >> ~/.bash_profile
    source ~/.bash_profile
    mkfile sample/dir test.file
    
    0 讨论(0)
  • 2020-12-24 13:04

    This might work:

    mkdir {{FOLDER NAME}}
    cd {{FOLDER NAME}}
    touch {{FOLDER NAME}}/file.txt
    
    0 讨论(0)
  • 2020-12-24 13:05
    mkdir B && touch B/myfile.txt
    

    Alternatively, create a function:

    mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }
    

    Execute it with 2 arguments: path to create and filename. Saying:

    mkfile B/C/D myfile.txt
    

    would create the file myfile.txt in the directory B/C/D.

    0 讨论(0)
  • 2020-12-24 13:05

    For this purpose, you can create your own function. For example:

    $ echo 'mkfile() { mkdir -p "$(dirname "$1")" && touch "$1" ;  }' >> ~/.bashrc
    $ source ~/.bashrc
    $ mkfile ./fldr1/fldr2/file.txt
    

    Explanation:

    • Insert the function to the end of ~/.bashrc file using the echo command
    • The -p flag is for creating the nested folders, such as fldr2
    • Update the ~/.bashrc file with the source command
    • Use the mkfile function to create the file
    0 讨论(0)
  • 2020-12-24 13:06

    add this to ~/.bashrc:

    function mkfile() { 
        mkdir -p  "$1" && touch  "$1"/"$2" 
    }
    

    save and then to make it available without a reboot or logout execute: $ source ~/.bashrc or you can just do:

    $ mkdir folder && touch $_/file.txt
    

    note that $_ = folder

    0 讨论(0)
提交回复
热议问题