使用 tee 命令将输出重定向到不存在的目录中的文件

18

我想使用 tee 命令将输出重定向到一个文件,并且我希望该文件被创建在一个尚未创建的目录中。

date | tee new_dir/new_file

当new_dir目录不存在时,tee命令会失败并显示以下消息:

tee: new_dir/new_file: No such file or directory

如果在运行tee命令之前手动创建new_dir目录,则可以成功执行,但由于某些原因,我不想手动创建new_dir目录,那么有没有可能使用tee命令来创建new_dir目录?

4个回答

29

不行。在运行 tee 命令之前,您需要先创建该目录。


1
目录在我的情况下已经存在,但是如果我不使用tee的-a标志,它会抱怨文件不存在。 - Alexander Mills

9

用一个能够为你创建目录的函数来替换tee

tee() { mkdir -p ${1%/*} && command tee "$@"; }

如果您希望该函数在使用简单文件名调用时起作用:

tee() { if test "$1" != "${1%/*}"; then mkdir -p ${1%/*}; fi &&
   command tee "$1"; }

tee foo.txt => mkdir -p foo.txt && command tee "foo.txt" 我觉得这不太对... - twalberg

1
mkdir ./new_dir && date | tee ./new_dir/new_file

由于这是tee命令,它同时将内容写入new_filestdout


0

嗯...经过一些实验,我发现了一些有趣的事情。

首先,让我们尝试触摸一些文件:

touch ~/.lein/profiles.clj

这个程序运行良好。但我们试着用引号包裹同样的内容:

touch "~/.lein/profiles.clj" # => touch: cannot touch ‘~/.lein/profiles.clj’: No such file or directory

所以,对于我的bash函数:

append_to_file() {
  echo $2 | tee -a $1
}

之后我将调用从中更改:

append_to_file '~/.lein/projects.clj' '{:user {:plugins [[lein-exec "0.3.1"]]}}'

传递给它(不带引号的第一个参数):

append_to_file ~/.lein/projects.clj '{:users {:plugins [[lein-exec "0.3.1"]]}}'

一切都很好。

更新

此案例将.lein视为现有目录。


5
touch "~/.lein/profiles.clj" 失败是因为双引号抑制了波浪线扩展。 - twalberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接