-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrnm.bash
More file actions
89 lines (79 loc) · 1.77 KB
/
Copy pathrnm.bash
File metadata and controls
89 lines (79 loc) · 1.77 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env bash
name="rnm"
print_usage() {
echo "Usage: $name [-h | --help] [-f | --force] [-c | --copy] <file> <new-filename>"
echo
echo "OPTIONS"
echo " -h, --help Display this help message"
echo " -f, --force Force rename if the new filename already exists"
echo " -c, --copy Copy instead of renaming"
}
# Transform long options to short ones for `getopts`
for arg in "$@"; do
shift
case "$arg" in
"--help")
set -- "$@" "-h"
;;
"--force")
set -- "$@" "-f"
;;
*)
set -- "$@" "$arg"
;;
esac
done
# Default behavior
force=false
copy=false
cmd_flags="-v"
while getopts ":hfc" opt; do
case ${opt} in
h)
print_usage
exit 0
;;
f)
force=true
;;
c)
copy=true
;;
*)
echo "Invalid option: $opt"
print_usage
exit 2
;;
esac
done
shift $((OPTIND - 1))
if [ $# -ne 2 ]; then
print_usage
exit 1
fi
# Parse and convert to absolute paths
# Using `realink` here because it converts to absolute path
# and remove both duplicate and trailing slashing
# which is tideous in pure Bash.
# Also, it resolve symbolic links which can be useful on a Nix system.
old_filename=$(readlink -n -e "$1")
new_filename=$(readlink -n -m "$(dirname "$old_filename")/$2")
if [ ! -e "$old_filename" ]; then
echo "Error: File '${old_filename}' does not exist"
exit 1
fi
if git ls-files --error-unmatch "$old_filename" &>/dev/null; then
if [ $copy == true ]; then
cp $cmd_flags "$old_filename" "$new_filename"
git add "$new_filename"
else
git mv $cmd_flags "$old_filename" "$new_filename"
fi
else
[ $force == true ] && cmd_flags="$cmd_flags -f"
if [ $copy == true ]; then
cp "$cmd_flags" "$old_filename" "$new_filename"
else
mv "$cmd_flags" "$old_filename" "$new_filename"
fi
fi