如果不存在,是否可以使mv创建要移动到的目录? [英] Is there a way to make mv create the directory to be moved to if it doesn't exist?

查看:2238
本文介绍了如果不存在,是否可以使mv创建要移动到的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果我位于主目录中,并且想将foo.c移至〜/bar/baz/foo.c,但是这些目录不存在,则可以通过某种方法自动创建这些目录,这样您只需输入

So, if I'm in my home directory and I want to move foo.c to ~/bar/baz/foo.c , but those directories don't exist, is there some way to have those directories automatically created, so that you would only have to type

mv foo.c ~/bar/baz/ 

一切都会成功吗?看来您可以将mv命名为一个简单的bash脚本,该脚本将检查那些目录是否存在,如果不存在,则先调用mkdir然后再调用mv,但是我想我会检查是否有人有更好的主意.

and everything would work out? It seems like you could alias mv to a simple bash script that would check if those directories existed and if not would call mkdir and then mv, but I thought I'd check to see if anyone had a better idea.

推荐答案

这种单线(以bash表示)如何:

How about this one-liner (in bash):

mkdir --parents ./some/path/; mv yourfile.txt $_

打破现状:

mkdir --parents ./some/path

创建目录(包括所有中间目录),然后:

creates the directory (including all intermediate directories), after which:

mv yourfile.txt $_

将文件移动到该目录($ _扩展到传递到上一个shell命令的最后一个参数,即:新创建的目录).

moves the file to that directory ($_ expands to the last argument passed to the previous shell command, ie: the newly created directory).

我不确定这在其他shell中能用多远,但可能会为您提供一些有关查找内容的想法.

I am not sure how far this will work in other shells, but it might give you some ideas about what to look for.

以下是使用此技术的示例:

Here is an example using this technique:

$ > ls
$ > touch yourfile.txt
$ > ls
yourfile.txt
$ > mkdir --parents ./some/path/; mv yourfile.txt $_
$ > ls -F
some/
$ > ls some/path/
yourfile.txt

这篇关于如果不存在,是否可以使mv创建要移动到的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆