add rmln
authorIan Kelling <ian@iankelling.org>
Fri, 9 Sep 2016 20:52:57 +0000 (13:52 -0700)
committerIan Kelling <ian@iankelling.org>
Fri, 9 Sep 2016 21:06:17 +0000 (14:06 -0700)
rmln [new file with mode: 0755]

diff --git a/rmln b/rmln
new file mode 100755 (executable)
index 0000000..98bd309
--- /dev/null
+++ b/rmln
@@ -0,0 +1,57 @@
+#!/bin/bash
+# Copyright (C) 2016 Ian Kelling
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+
+#     http://www.apache.org/licenses/LICENSE-2.0
+
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+rmln () {
+    local help="Usage: rmln [RM_OPTION]... FILE...
+wrap rm, expanding symlink arguments
+
+Symlink arguments are recursively expanded so the links and the targets
+are removed.  All arguments to rm work.
+
+rm's --help:
+"
+    local file targets
+
+    # simple but correct counting past gnu rm options
+    local -i index=1
+    local options=true
+    local helped=false # only print our help once
+    while $options; do
+        if [[ "${@:index:1}" == -* ]]; then
+            if [[ "${@:index:1}" == --help ]] && ! $helped; then
+                echo "$help"
+                helped=true
+            fi
+            if [[ "${@:index:1}" == -- ]]; then
+                options=false
+            fi
+            index+=1
+        else
+            options=false
+        fi
+    done
+
+    for file in "${@:index}"; do
+        [[ -L "$file" ]] && _rmln_recurse "$file"
+    done
+    rm "$@" "${targets[@]}"
+}
+
+_rmln_recurse() {
+    local x="$( readlink "$1" )"
+    targets+=( "$x" )
+    [[ -L $x ]] && _rmln_recurse "$x"
+}
+rmln "$@"