所以,如果我在我的主目录下,我想把foo.c移动到~/bar/baz/foo.c,但是这些目录不存在,有没有什么方法可以自动创建这些目录,这样你只需要输入

mv foo.c ~/bar/baz/ 

一切都会解决的吗?似乎可以将mv别名为一个简单的bash脚本,该脚本将检查这些目录是否存在,如果不存在,将调用mkdir,然后调用mv,但我想检查一下,看看是否有人有更好的主意。


当前回答

根据另一个答案的注释,这是我的shell函数。

# mvp = move + create parents
function mvp () {
    source="$1"
    target="$2"
    target_dir="$(dirname "$target")"
    mkdir --parents $target_dir; mv $source $target
}

将它包含在.bashrc或类似文件中,这样你就可以在任何地方使用它。

其他回答

((cd src-path && tar --remove-files -cf - files-to-move) | ( cd dst-path && tar -xf -))

在将文件批量移动到新的子目录时,我经常遇到这个问题。理想情况下,我想这样做:

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

我在linux上用install命令完成了这一点:

root@logstash:# myfile=bash_history.log.2021-02-04.gz ; install -v -p -D $myfile /tmp/a/b/$myfile

bash_history.log.2021-02-04.gz -> /tmp/a/b/bash_history.log.2021-02-04.gz

唯一的缺点是文件权限被改变了:

root@logstash:# ls -lh /tmp/a/b/

-rwxr-xr-x 1 root root 914 Fev  4 09:11 bash_history.log.2021-02-04.gz

如果你不介意重置权限,你可以使用:

-g, --group=GROUP   set group ownership, instead of process' current group
-m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x
-o, --owner=OWNER   set ownership (super-user only)

你可以使用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 "$@"