必要时创建新文件及其父目录的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:50:20  来源:igfitidea点击:

Bash command to create a new file and its parent directories if necessary

bashshell

提问by Peng Zhang

With the -p(--parents) option, mkdircreates parent directories if necessary.

使用-p( --parents) 选项,mkdir在必要时创建父目录。

touch, vimor >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 -pdoes 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 ""