diff options
author | Tom Ryder <tom@sanctum.geek.nz> | 2016-08-20 13:52:55 +1200 |
---|---|---|
committer | Tom Ryder <tom@sanctum.geek.nz> | 2016-08-20 13:54:09 +1200 |
commit | a4e4cf23ca984e1fc7633b48f94c1795a5bc7ec8 (patch) | |
tree | 4084793d32dcc0264846cf8f1207722c56cec99c /sh | |
parent | Correctly bail from failed subshell (diff) | |
download | dotfiles-a4e4cf23ca984e1fc7633b48f94c1795a5bc7ec8.tar.gz dotfiles-a4e4cf23ca984e1fc7633b48f94c1795a5bc7ec8.zip |
Port pd() to POSIX sh
Diffstat (limited to 'sh')
-rw-r--r-- | sh/shrc.d/pd.sh | 37 |
1 files changed, 37 insertions, 0 deletions
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 -- "$@" +} |