如果需要,如何在一行中触摸文件和 mkdir

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

我需要touch一个绝对文件名的文件,例如:/opt/test/test.txt,但我不确定系统中是否存在/opt/test。所以代码应该类似于:

if (-d '/opt/test') {
    touch '/opt/test/test.txt';
} else {
    mkdir -p '/opt/test';
    touch '/opt/test/test.txt'
}

有没有更好的方法来简化代码?我希望有一些系统命令可以只用一行完成同样的工作。

在 shell 脚本中,您可以简单地执行以下操作:

mkdir -p /opt/test && touch /opt/test/test.txt
如果目录已经存在,

mkdir -p 不会失败(也不会做任何事情)。

在 perl 中,使用 File::Path 模块中的 make_path,然后根据需要创建文件。 make_path 如果目录已经存在,也不会执行任何操作,因此无需自行检查。

在 perl 中,使用我最喜欢的模块之一:Path::Tiny

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

来自文档:

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

命令行中的 Perl,

perl -MFile::Basename -MFile::Path=make_path -e'
  make_path(dirname($_)), open(F, ">>", $_) for pop;
' /opt/test/test.txt
mkdir B && touch B/myfile.txt

或者,创建一个函数:

   mkfile() { 
    mkdir -p $( dirname "") && touch "" 
   }

使用 1 个参数执行它:文件路径。说:

mkfile B/C/D/myfile.txt

将在目录 B/C/D 中创建文件 myfile.txt。

将 Python 带到命令行。

即使用 pyp

 cat filepaths.txt | pyp "'mkdir -p '+s[0:-1]|s+'; touch '+o" | sh

The Pyed Piper" 或 pyp,是一个 linux 类似于 awk 或 sed 的命令行文本操作工具,但它使用标准的 python 字符串和列表方法以及演变而来的自定义函数在紧张的生产环境中快速产生结果。

我在 ~/.bash_aliases 中定义了一个 touchp:

function touchp() {
  /bin/mkdir -p "$(dirname "")/" && /usr/bin/touch ""
}

如果不存在,它会在文件上方静默创建结构,并且在传递单个文件名且前面没有任何目录时使用它是非常安全的。

我不太喜欢打字,所以我把这个命令放到我的 .profile 中一个命名的 fn 中,但在我这样做之前我已经使用了这个公式多年:

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

变量$_ 存储上一个命令的最后一个参数。了解整体情况非常方便。

我的 .zshalias 文件中有这个 shell 函数:

function touch-safe {
    for f in "$@"; do
      [ -d $f:h ] || mkdir -p $f:h && command touch $f
    done
}
alias touch=touch-safe

如果 testmkdir 命令失败,则不会调用任何 touch 命令。