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

前端 未结 8 1020
抹茶落季
抹茶落季 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 15:03

    In perl, using one of my favorite module: Path::Tiny.

    path("/opt/test/test.txt")->touchpath;
    

    From the doc:

    Combines mkpath and touch. Creates the parent directory if it doesn't exist, before touching the file.

    0 讨论(0)
  • 2021-02-18 15:06

    I like typing very little, so I put this command into a named fn in my .profile, but I used this formulation for years before I did it:

    mkdir -p dirname/sub/dir && touch $_/filename.ext

    The variable $_ stores the last argument to the previous command. Pretty handy to know about overall.

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