我想使用 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目录?
不行。在运行 tee
命令之前,您需要先创建该目录。
用一个能够为你创建目录的函数来替换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"
我觉得这不太对... - twalbergmkdir ./new_dir && date | tee ./new_dir/new_file
由于这是tee
命令,它同时将内容写入new_file
和stdout
嗯...经过一些实验,我发现了一些有趣的事情。
首先,让我们尝试触摸一些文件:
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
视为现有目录。
touch "~/.lein/profiles.clj"
失败是因为双引号抑制了波浪线扩展。 - twalberg