【发布时间】:2012-02-12 19:14:41
【问题描述】:
我正在尝试制作一个 bash 脚本,将文件或目录从源目录移动到目标目录,并将符号链接放入源目录。
所以,<source_path> 可以是文件或目录,<destination_dir_path> 是我希望将原始文件移动到的目录。
示例用法:
$ 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
并且该目录没有移动到destination_directory,而只是移动了它的内容。
#!/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%/}"
有人可以帮忙吗?
【问题讨论】:
-
定义“不能正常工作”。
-
是的,我已经编辑了这个问题。谢谢。
-
到目前为止,我测试你的脚本似乎工作正常!
标签: linux bash shell move symlink