我正在尝试制作一个 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/