From f4b0a07091e4a10395f98726bc075f2eaae1469f Mon Sep 17 00:00:00 2001 From: Lorenzo Beretta Date: Wed, 9 Jun 2021 23:24:12 +0200 Subject: [PATCH] Translate to (99%) POSIX sh The missing 1% is that POSIX doesn't have "local" or a __clean__ (non kludgy) equivalent. Other than that I'm checking the return value of everything that could conceivably fail, except for `$(pwd)` which imho could be replaced by `$PWD`. Autocompletion is commented out in case you use a non-bash shell which has autocompletion (OpenBSD's ksh at least) and feel like translating that. --- upto-posix.sh | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 upto-posix.sh diff --git a/upto-posix.sh b/upto-posix.sh new file mode 100644 index 0000000..88ee806 --- /dev/null +++ b/upto-posix.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# shellcheck "$0" +upto() { + # "local" isn't POSIX technically... + local EXPRESSION="$1" + if [ -z "$EXPRESSION" ]; then + echo "A folder expression must be provided." >&2 + return 1 + fi + if [ "$EXPRESSION" = "/" ]; then + cd "/" + return #0 + fi + local CURRENT_FOLDER="$(pwd)" # why not $PWD? + local MATCHED_DIR="" + local MATCHING=true + + while [ "$MATCHING" = true ]; do + case "$CURRENT_FOLDER" in + (*${EXPRESSION}*) + MATCHED_DIR="$CURRENT_FOLDER" + CURRENT_FOLDER=$(dirname "$CURRENT_FOLDER") || return + ;; + (*) + MATCHING=false ;; + esac + done + if [ -n "$MATCHED_DIR" ]; then + cd "$MATCHED_DIR" + return #0 + else + echo "No Match." >&2 + return 1 + fi +} + +# complete upto +#_upto () { +# # necessary locals for _init_completion +# local cur prev words cword +# _init_completion || return +# +# COMPREPLY+=( $( compgen -W "$( echo ${PWD//\// } )" -- $cur ) ) +#} +## This complete scheme relies on bash_completion, and the subsequent +## _init_completion function to work. +#declare -f _init_completion > /dev/null && complete -F _upto upto