bf497615a23b7196700cbfc75767b1606762f5e3
[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 [--help] LN_ARGUMENTS...
7 Create symlinks conveniently and forcefully.
8 Remove existing file/links using trash-put or rm -rf if it is not available.
9 Create directory if needed. Small change to ln argument semantics: for 2 arguments,
10 the second is the link, never a directory to put the link in.
11 LN_ARGUMENTS are passed to ln -s --, meaning no ln option arguments are supported."
12 if [[ $1 == --help ]]; then
13 echo "$help"
14 return 0
15 fi
16
17 local remove x
18 if type -P dircolors >/dev/null; then
19 remove=trash-put
20 else
21 remove="rm -rf"
22 fi
23
24 if [[ $# -ge 3 ]]; then
25 if [[ -d ${!#} ]]; then
26 local oldcwd=$PWD
27 cd ${!#} # last arg
28 for x in "${@:1:$(($#-1))}"; do # all but last arg
29 # remove any trailing slashes
30 x="${x%%+(/)}"
31 # remove any leading directory components
32 x="${x##*/}"
33 [[ -e "$x" || -L "$x" ]] && $remove "$x"
34 done
35 cd "$oldcwd"
36 else
37 mkdir -p "${!#}"
38 fi
39 elif [[ $# -eq 2 ]]; then
40 if [[ -e "$2" || -L "$2" ]]; then
41 $remove "$2"
42 elif [[ ! -d "$2/.." ]]; then
43 mkdir -p "$2/.."
44 fi
45 elif [[ $# -eq 1 ]]; then
46 [[ -e "${1##*/}" || -L "${1##*/}" ]] && $remove "${1##*/}"
47 fi
48 ln -s -- "$@"
49 }
50 lnf "$@"