From a4e4cf23ca984e1fc7633b48f94c1795a5bc7ec8 Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Sat, 20 Aug 2016 13:52:55 +1200 Subject: Port pd() to POSIX sh --- sh/shrc.d/pd.sh | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 sh/shrc.d/pd.sh (limited to 'sh/shrc.d/pd.sh') diff --git a/sh/shrc.d/pd.sh b/sh/shrc.d/pd.sh new file mode 100644 index 00000000..c022b1e8 --- /dev/null +++ b/sh/shrc.d/pd.sh @@ -0,0 +1,37 @@ +# Attempt to change into the argument's parent directory; This is intended for +# use when you've got a file path in a variable, or in history, or in Alt+., +# and want to quickly move to its containing directory. In the absence of an +# argument, this just shifts up a directory, i.e. `cd ..` +pd() { + + # Change the positional parameters from the target to its containing + # directory + set -- "$( + + # Check argument count + if [ "$#" -gt 1 ] ; then + printf >&2 'pd(): Too many arguments\n' + exit 2 + fi + + # Figure out target dirname + dirname=${1:-..} + dirname=${dirname%/} + dirname=${dirname%/*} + + # Check we have a target after that + if [ -z "$dirname" ] ; then + printf >&2 'ud(): Destination construction failed\n' + exit 1 + fi + + # Print the target + printf '%s\n' "$dirname" + )" + + # If the subshell printed nothing, return with failure + [ -n "$1" ] || return + + # Try to change into the determined directory + command cd -- "$@" +} -- cgit v1.2.3