linux - Bash: move 文件/目录并创建它的链接

标签 linux bash shell move symlink

我正在尝试制作一个 bash 脚本,将文件或目录从源目录 move 到目标目录,并将指向它的符号链接(symbolic link)放入源目录。

所以,<source_path>可以是文件或目录,<destination_dir_path>是我要将原件 move 到的目录。

示例用法:

$ mvln /source_dir/file.txt /destination_dir/
OR
$ mvln /source_dir/dir_I_want_to_move/ /destination_dir/

这是我设法组合起来的,但它不能正常工作。 仅当 source 是目录时才有效,否则 mv 返回错误:

mv: unable to rename `/source_dir/some_file.txt': Not a directory

并且该目录不会 move 到 destination_directory,而只会 move 其内容。

#!/bin/bash

SCRIPT_NAME='mvln'
USAGE_STRING='usage: '$SCRIPT_NAME' <source_path> <destination_dir_path>'

# Show usage and exit with status
show_usage_and_exit () {
    echo $USAGE_STRING
    exit 1
}

# ERROR file does not exist
no_file () {
    echo $SCRIPT_NAME': '$1': No such file or directory'
    exit 2
}

# Check syntax
if [ $# -ne 2 ]; then
    show_usage_and_exit
fi

# Check file existence
if [ ! -e "$1" ]; then
    no_file $1
fi

# Get paths
source_path=$1
destination_path=$2

# Check that destination ends with a slash
[[ $destination_path != */ ]] && destination_path="$destination_path"/

# Move source
mv "$source_path" "$destination_path"

# Get original path
original_path=$destination_path$(basename $source_path)

# Create symlink in source dir
ln -s "$original_path" "${source_path%/}"

有人可以帮忙吗?

最佳答案

问题是 $destination_path 引用了一个不存在的目录。像这样:

mv /path/to/file.txt /path/to/non/existent/directory/

返回一个错误,并且

mv /path/to/directory/ /path/to/non/existent/directory/

会将/path/to/directory/重命名为/path/to/non/existent/directory/(前提是/path/to/non/existent/ 是一个存在的目录,只是没有名为 directory 的子文件夹。

如果您期望 $destination_path 不存在,那么您可以添加一个 mkdir 命令:

mkdir "$destination_path"
mv "$source_path" "$destination_path"

如果您预计它可能不存在,那么您可以有条件地添加它:

[[ -d "$destination_path" ]] || mkdir "$destination_path"
mv "$source_path" "$destination_path"

如果您期望它确实存在,那么您需要进行一些调试!

(顺便说一下,根据您的具体情况,您可能会发现 mkdir -p 很有帮助。它递归地创建一个目录所有必要的父目录,以及它不介意目录是否已经存在。)

关于linux - Bash: move 文件/目录并创建它的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9251818/

相关文章:

linux - 目录中行数最多的文件不是字节

linux - 为什么 shell 在后台进程中忽略 SIGINT 和 SIGQUIT?

linux - 从哪里获得完整的联机帮助页

windows - Windows 开发人员切换到 Linux 的资源

linux - VIM 中的自动代码完成?

bash - ~/.inputrc 中忽略 "set completion-ignore-case on "

Bash:获取文件类型的标准程序

linux - 如何使用命令或脚本在文本文件中放置分隔符

linux - Bash - 搜索和追加字符串

bash - Netbeans "Remote Terminal Tab"alt/ctrl 和其他组合键不起作用