daae096c035f51d63500a5f526d79403e260a6ee
[lnf] / lnf-function
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 local reset_extglob=false
26 ! shopt extglob >/dev/null && reset_extglob=true
27 shopt -s extglob
28
29
30 local remove x
31 if type -P trash-put >/dev/null; then
32 remove=trash-put
33 else
34 remove="rm -rf"
35 fi
36
37 if $nodir && [[ $# -eq 2 ]]; then
38 if [[ -e "$2" || -L "$2" ]]; then
39 $remove "$2"
40 elif [[ ! -d "$2/.." ]]; then
41 mkdir -p "$2/.."
42 fi
43 elif [[ $# -ge 2 ]]; then
44 if [[ -d ${!#} ]]; then
45 local oldcwd=$PWD
46 cd "${!#}" # last arg
47 for x in "${@:1:$(( $# - 1 ))}"; do # all but last arg
48 # remove any trailing slashes, uses extglob
49 x="${x%%+(/)}"
50 # remove any leading directory components
51 x="${x##*/}"
52 [[ -e "$x" || -L "$x" ]] && $remove "$x"
53 done
54 cd "$oldcwd"
55 else
56 mkdir -p "${!#}"
57 fi
58 elif [[ $# -eq 1 ]]; then
59 [[ -e "${1##*/}" || -L "${1##*/}" ]] && $remove "${1##*/}"
60 fi
61
62 $reset_extglob && shopt -u extglob
63 ln -s -- "$@"
64 }