Bash 重定向并附加到不存在的文件/目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21052925/
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 redirect and append to non-existent file/directory
提问by CMCDragonkai
When I use >> nonexistent/file.log
. Bash gives me back "No such file or directory".
当我使用>> nonexistent/file.log
. Bash 给我回复“没有这样的文件或目录”。
How can I make a one liner that redirects the STDOUT/STDERR to a log file, even if it doesn't exist? If it doesn't exist, it must create the necessary folders and files.
我怎样才能制作一个将 STDOUT/STDERR 重定向到日志文件的单行代码,即使它不存在?如果它不存在,它必须创建必要的文件夹和文件。
回答by Gilles Quenot
Using install
:
使用install
:
command | install -D /dev/stdin nonexistent/file.log
or use
或使用
mkdir nonexistent
first.
第一的。
回答by Piranna
You can use dirname
to get the base path of the file, and later use it with mkdir -p
. After that you can do the redirection:
您可以使用dirname
获取文件的基本路径,然后将其与mkdir -p
. 之后,您可以进行重定向:
sh
mkdir -p `dirname nonexistent/file.log`
echo blah >> nonexistent/file.log
sh
mkdir -p `dirname nonexistent/file.log`
echo blah >> nonexistent/file.log
回答by MerrillFraz
If this is run multiple times, and only the first time will the directory be missing, might want to check for it first (before you start your expect stuff)
如果多次运行,并且只有第一次会丢失目录,则可能需要先检查它(在您开始预期的东西之前)
if [ ! -d ~/nonexistent ]
then mkdir ~/nonexistent
fi
Then use the other examples posted to simply scp the resulting file you create with ls
back to your host box in the newly created directory.
然后使用发布的其他示例简单地将您创建的结果文件 scpls
返回到新创建目录中的主机箱。
回答by Fourdee
To automatically generate all the directories for a filepath:
要自动生成文件路径的所有目录:
FILEPATH="/folder1/folder2/myfile.txt"
if [ ! -f "$FILEPATH" ]; then
mkdir -p "$FILEPATH"
rm -r "$FILEPATH"
fi
#/folder1/folder2 has now been created.