-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmv-and-link-back
executable file
·67 lines (57 loc) · 1.44 KB
/
mv-and-link-back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/zsh
if [[ $# -lt 2 ]]; then
echo "Usage: mv-and-link-back <source>... <target>"
exit 1
fi
target=$argv[$#]
sources=($argv[1,-2])
remove_trailing_slashes() {
a=$1
while [[ $a =~ '/$' ]]; do
a=${a%/}
done
echo $a
}
relpath() {
python -c "import os.path; print os.path.relpath('$1','${2:-$PWD}')"
}
# Remove trailing slashes from target
target=$(remove_trailing_slashes $target)
# target has to be a directory when having multiple sources
if [[ $#sources > 1 ]]; then
if ! [[ -d $target ]]; then
echo "Error: target is not a directory. But there are multiple sources."
exit 1
fi
fi
for source in $sources; do
if [[ -L $source ]]; then
echo "Warning: source is a symbolic link already, skipping: $source"
continue
fi
source_resolved=$(readlink -f $source) # resolve e.g. "." and ".."
[[ -n $source_resolved ]] && source=$source_resolved
source=$(remove_trailing_slashes $source) # this might be necessary when "readlink -f" fails
if [[ -d $target ]] ; then
mv_to=$target/$source:t
else
mv_to=$target
fi
if [[ -e $mv_to ]] ; then
echo "Error: target already exists: $mv_to"
exit 2
fi
# if [[ $source -ef $mv_to ]]; then
# echo "Error: source and target are the same file already"
# exit 1
# fi
# move:
cmd=(mv $source $mv_to)
echo "DEBUG: $cmd"
$cmd
# link:
link_to=$(relpath $mv_to $source:h)
cmd=(ln -s $link_to $source)
echo "DEBUG: $cmd"
$cmd
done