所以,如果我在我的主目录下,我想把foo.c移动到~/bar/baz/foo.c,但是这些目录不存在,有没有什么方法可以自动创建这些目录,这样你只需要输入
mv foo.c ~/bar/baz/
一切都会解决的吗?似乎可以将mv别名为一个简单的bash脚本,该脚本将检查这些目录是否存在,如果不存在,将调用mkdir,然后调用mv,但我想检查一下,看看是否有人有更好的主意。
所以,如果我在我的主目录下,我想把foo.c移动到~/bar/baz/foo.c,但是这些目录不存在,有没有什么方法可以自动创建这些目录,这样你只需要输入
mv foo.c ~/bar/baz/
一切都会解决的吗?似乎可以将mv别名为一个简单的bash脚本,该脚本将检查这些目录是否存在,如果不存在,将调用mkdir,然后调用mv,但我想检查一下,看看是否有人有更好的主意。
当前回答
Rsync命令只能在目标路径的最后一个目录不存在的情况下才能实现,例如,对于目标路径~/bar/baz/,如果bar存在而baz不存在,则可以使用以下命令:
Rsync -av——remove-source-files foo.c ~/bar/baz/
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X)
-v, --verbose increase verbosity
--remove-source-files sender removes synchronized files (non-dir)
在这种情况下,如果baz目录不存在,将创建它。但如果bar和baz都不存在,rsync将失败:
sending incremental file list
rsync: mkdir "/root/bar/baz" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at main.c(657) [Receiver=3.1.2]
所以基本上使用rsync -av——remove-source-files作为mv的别名应该是安全的。
其他回答
$what=/path/to/file;
$dest=/dest/path;
mkdir -p "$(dirname "$dest")";
mv "$what" "$dest"
你可以使用mkdir:
mkdir -p ~/bar/baz/ && \
mv foo.c ~/bar/baz/
一个简单的脚本自动完成(未经测试):
#!/bin/sh
# Grab the last argument (argument number $#)
eval LAST_ARG=\$$#
# Strip the filename (if it exists) from the destination, getting the directory
DIR_NAME=`echo $2 | sed -e 's_/[^/]*$__'`
# Move to the directory, making the directory if necessary
mkdir -p "$DIR_NAME" || exit
mv "$@"
在将文件批量移动到新的子目录时,我经常遇到这个问题。理想情况下,我想这样做:
mv * newdir/
这个线程中的大多数答案都建议mkdir然后mv,但这导致:
mkdir newdir && mv * newdir
mv: cannot move 'newdir/' to a subdirectory of itself
我面临的问题略有不同,因为我想全面移动所有内容,并且,如果我在移动之前创建了新目录,那么它也会尝试将新目录移动到自己。所以,我通过使用父目录来解决这个问题:
mkdir ../newdir && mv * ../newdir && mv ../newdir .
警告:不能在根文件夹(/)中工作。
mkdir -p `dirname /destination/moved_file_name.txt`
mv /full/path/the/file.txt /destination/moved_file_name.txt
((cd src-path && tar --remove-files -cf - files-to-move) | ( cd dst-path && tar -xf -))