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

前端 未结 8 1234
抹茶落季
抹茶落季 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:50

    In a shell script, you can simply do:

    mkdir -p /opt/test && touch /opt/test/test.txt
    

    mkdir -p will not fail (and won't do anything) if the directory already exists.

    In perl, use make_path from the File::Path module, then create the file however you want. make_path also doesn't do anything if the directory exists already, so no need to check yourself.

提交回复
热议问题