c907b6246416e27a6bbb0d5b9fa6cf9d7922c61b
[lnf] / lnf
1 #!/bin/bash
2 # Copyright (C) 2014 Ian Kelling
3 # This program is under GPL v. 3 or later, see <http://www.gnu.org/licenses/>
4
5 lnf() {
6 local help="lnf - Create symlinks conveniently and forcefully.
7 Usage:
8 lnf -T TARGET LINK_NAME (1st form)
9 lnf TARGET (2nd form)
10 lnf TARGET... DIRECTORY (3rd form)
11
12 Remove existing file in the using trash-put or rm -rf if it is not available.
13 Create directory if needed. Slightly more restrictive arguments than ln.
14
15 In the 1st form, create a link to TARGET with the name LINK_NAME. In the 2nd
16 form, create a link to TARGET in the current directory. In the 3rd form, create
17 links to each TARGET in DIRECTORY."
18
19 if [[ $1 == --help || $# -eq 0 ]]; then
20 echo "$help"
21 return 0
22 fi
23
24 local nodir
25 if [[ $1 == -T ]]; then
26 nodir=-T
27 shift
28 if (( $# != 2 )); then
29 echo "lnf error: expected 2 arguments with -T flag. Got $#"
30 return 1
31 fi
32 fi
33
34 local reset_extglob=false
35 ! shopt extglob >/dev/null && reset_extglob=true
36 shopt -s extglob
37
38
39 local remove x
40 if type -P trash-put >/dev/null; then
41 remove=trash-put
42 else
43 remove="rm -rf"
44 fi
45
46 if [[ $nodir ]]; then
47 if [[ -e "$2" || -L "$2" ]]; then
48 $remove "$2"
49 elif ! mkdir -p "$(dirname "$2")"; then
50 echo "lnf error: failed to make directory $(dirname "$2")"
51 return 1
52 fi
53 elif (( $# >= 2 )); then
54 if [[ -d ${!#} ]]; then
55 local oldcwd=$PWD
56 cd "${!#}" # last arg
57 for x in "${@:1:$(( $# - 1 ))}"; do # all but last arg
58 # remove any trailing slashes, uses extglob
59 x="${x%%+(/)}"
60 # remove any leading directory components
61 x="${x##*/}"
62 [[ -e "$x" || -L "$x" ]] && $remove "$x"
63 done
64 cd "$oldcwd"
65 else
66 if ! mkdir -p "${!#}"; then
67 echo "lnf error: failed to make directory ${!#}"
68 return 1
69 fi
70 fi
71 elif [[ $# -eq 1 ]]; then
72 [[ -e "${1##*/}" || -L "${1##*/}" ]] && $remove "${1##*/}"
73 fi
74
75 $reset_extglob && shopt -u extglob
76 ln -s $nodir -- "$@"
77 }
78 lnf "$@"