How to touch a file and mkdir if needed in one line

前端 未结 8 1017
抹茶落季
抹茶落季 2021-02-18 14:38

I need to touch a file with an absolute file name such as: /opt/test/test.txt, but I\'m not sure if there is /opt/test existed on the system. So the code should similar with thi

8条回答
  •  天涯浪人
    2021-02-18 14:39

    mkdir B && touch B/myfile.txt
    

    Alternatively, create a function:

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

    Execute it with 1 arguments: filepath. Saying:

    mkfile B/C/D/myfile.txt
    

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

提交回复
热议问题