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