必要时创建新文件及其父目录的 Bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24666330/
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
Bash command to create a new file and its parent directories if necessary
提问by Peng Zhang
With the -p
(--parents
) option, mkdir
creates parent directories if necessary.
使用-p
( --parents
) 选项,mkdir
在必要时创建父目录。
touch
, vim
or >
can create new files in bash, but only when the parent directories exist.
touch
, vim
或者>
可以在 bash 中创建新文件,但仅当父目录存在时。
How to create a new file and its parent directories if necessary, in one command?Just like what the -p
does for mkdir
如果需要,如何在一个命令中创建一个新文件及其父目录?就像做什么-p
一样mkdir
采纳答案by linuts
install is your friend:
安装是你的朋友:
install -Dv /dev/null some/new/path/base-filename
回答by mklement0
Here's a shell function:
这是一个shell函数:
mkfileP() { mkdir -p "$(dirname "")" || return; touch ""; }
# Sample call
mkfileP "./newSubDir/test.txt" && echo 'created or touched' || echo 'failure'
You can place it in your shell profile, for instance.
例如,您可以将它放在您的 shell 配置文件中。
Alternatively, implement it as a script(add error handling and command-line help as needed):
或者,将其实现为脚本(根据需要添加错误处理和命令行帮助):
#!/usr/bin/env bash
mkdir -p "$(dirname "")" || exit
touch ""