bash 如何在shell脚本中创建文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7818592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a file in shell script
提问by xyz
I need to write a shell script where I read a variable from environment. If the file pointed by it doesn't exist, I want to create it.
我需要编写一个 shell 脚本来从环境中读取一个变量。如果它指向的文件不存在,我想创建它。
This file path could contain some intermediate non-existent directories, so these also need to be created. So neither mkdir -p works here nor simple touch works here.
此文件路径可能包含一些中间不存在的目录,因此也需要创建这些目录。所以 mkdir -p 在这里不起作用,简单的触摸在这里也不起作用。
What is the workaround?
解决方法是什么?
Thanks!
谢谢!
回答by Fred Foo
mkdir -p "`dirname $foo`"
touch "$foo"
dirnameworks on arbitrary paths; it doesn't check whether the path is in use (whether the file pointed to exists).
dirname适用于任意路径;它不检查路径是否在使用中(指向的文件是否存在)。
回答by Irfan
Why not combine both? mkdir -p /directories/.... && touch /directories/file
为什么不把两者结合起来? mkdir -p /directories/.... && touch /directories/file

