BASH 重定向创建文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9022383/
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 create folder
提问by Baruch
How can I have the following command
我怎样才能有以下命令
echo "something" > "$f"
where $fwill be something like folder/file.txtcreate the folder folderif does not exist?
如果不存在,$f将在哪里folder/file.txt创建文件夹folder?
If I can't do that, how can I have a script duplicate all folders (without contents) in directory 'a' to directory 'b'?
如果我不能这样做,我怎样才能让脚本将目录“a”中的所有文件夹(没有内容)复制到目录“b”?
e.g if I have
例如,如果我有
a/f1/
a/f2/
a/f3/
a/f1/
a/f2/
a/f3/
I want to have
我希望有
b/f1/
b/f2/
b/f3/
b/f1/
b/f2/
b/f3/
采纳答案by jordanm
The other answers here are using the external command dirname. This can be done without calling an external utility.
这里的其他答案是使用外部命令dirname。这可以在不调用外部实用程序的情况下完成。
mkdir -p "${f%/*}"
You can also check if the directory already exists, but this not really required with mkdir -p:
您还可以检查目录是否已经存在,但这并不是真正需要的mkdir -p:
mydir="${f%/*}"
[[ -d $mydir ]] || mkdir -p "$mydir"
回答by Alex Gitelman
try
尝试
mkdir -p `dirname $f` && echo "something" > $f
回答by dogbane
You can use mkdir -pto create the folder before writing to the file:
您可以使用mkdir -p在写入文件之前创建文件夹:
mkdir -p "$(dirname $f)"
回答by shock_one
echo "something" | install -D /dev/stdin $f

