aboutsummaryrefslogtreecommitdiff
path: root/sh
diff options
context:
space:
mode:
authorTom Ryder <tom@sanctum.geek.nz>2016-08-20 12:08:31 +1200
committerTom Ryder <tom@sanctum.geek.nz>2016-08-20 12:09:36 +1200
commit304f4afceef0d421f2bba1ab9acff98fc83b000d (patch)
tree129ecdcae789e82a609ab0c76667d4ced768b1fe /sh
parentRemove OLDPWD hack (diff)
downloaddotfiles-304f4afceef0d421f2bba1ab9acff98fc83b000d.tar.gz
dotfiles-304f4afceef0d421f2bba1ab9acff98fc83b000d.zip
Port bd() to POSIX sh
Diffstat (limited to 'sh')
-rw-r--r--sh/shrc.d/bd.sh67
1 files changed, 67 insertions, 0 deletions
diff --git a/sh/shrc.d/bd.sh b/sh/shrc.d/bd.sh
new file mode 100644
index 00000000..0d1abbcf
--- /dev/null
+++ b/sh/shrc.d/bd.sh
@@ -0,0 +1,67 @@
+# Move back up the directory tree to the first directory matching the name
+bd() {
+
+ # Set positional parameters to an option terminator and what will hopefully
+ # end up being a target directory
+ set -- -- "$(
+
+ # If the first of the existing positional arguments is --, shift it
+ # off
+ [ "$1" = -- ] && shift
+
+ # There's no more than one argument after that
+ [ "$#" -le 1 ] || exit 1
+
+ # The requested pattern is the first argument, defaulting to just the
+ # parent directory
+ req=${1:-..}
+
+ # Strip trailing slashes if a trailing slash isn't the whole pattern
+ [ "$req" = / ] || req=${req%/}
+
+ # What to do now depends on the request
+ case $req in
+
+ # Just go straight to the root or dot directories if asked
+ /|.|..)
+ dirname=$req
+ ;;
+
+ # Anything with a leading / needs to anchor to the start of the
+ # path. A strange request though. Why not just use cd?
+ /*)
+ dirname=$req
+ case $PWD in
+ "$dirname"/*) ;;
+ *) dirname='' ;;
+ esac
+ ;;
+
+ # In all other cases, iterate through the PWD to find a match, or
+ # whittle the target down to an empty string trying
+ *)
+ dirname=$PWD
+ while [ -n "$dirname" ] ; do
+ dirname=${dirname%/*}
+ case $dirname in
+ */"$req") break ;;
+ esac
+ done
+ ;;
+ esac
+
+ # Check we have a target after all that
+ if [ -z "$dirname" ] ; then
+ printf >&2 'bd(): Directory name not in path\n'
+ exit 1
+ fi
+
+ # Print the target
+ printf '%s\n' "$dirname"
+
+ # If the subshell failed, return from the function with the same exit value
+ )" || return
+
+ # Try to change into the determined directory
+ command cd "$@"
+}