From 162f108b44470d34d2dec149b295c6d2a8356d6d Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Wed, 29 Mar 2017 10:50:26 +1300 Subject: Add gt() (go to) --- README.markdown | 3 ++- sh/shrc.d/gt.sh | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 sh/shrc.d/gt.sh diff --git a/README.markdown b/README.markdown index 8b95e1a9..874e0fc2 100644 --- a/README.markdown +++ b/README.markdown @@ -180,10 +180,11 @@ in `sh/shrc.d` to be loaded by any POSIX interactive shell. Those include: * `gd()` goes to the marked directory. * `pmd()` prints the marked directory. * `xd()` swaps the current and marked directories. -* Nine other directory management and navigation functions: +* Ten other directory management and navigation functions: * `ad()` is a `cd` shortcut accepting targets like `/u/l/b` for `/usr/local/bin`, as long as they are unique. * `bd()` changes into a named ancestor of the current directory. + * `gt()` changes into a directory or into a file's directory. * `mkcd()` creates a directory and changes into it. * `pd()` changes to the argument's parent directory. * `rd()` replaces the first instance of its first argument with its diff --git a/sh/shrc.d/gt.sh b/sh/shrc.d/gt.sh new file mode 100644 index 00000000..d18a4ab8 --- /dev/null +++ b/sh/shrc.d/gt.sh @@ -0,0 +1,28 @@ +# If the argument is a directory, change to it. If it's a file, change to its +# parent. Stands for "get to". +gt() { + + # Check argument count + if [ "$#" -gt 1 ] ; then + printf >&2 'gd(): Too many arguments\n' + return 2 + fi + + # Strip trailing slash + set -- "${1%/}" + + # If target doesn't have a leading slash, add PWD prefix + case $1 in + /*) ;; + *) set -- "${PWD%/}"/"$1" + esac + + # If target isn't a directory, chop to its parent + [ -d "$1" ] || set -- "${1%/*}" + + # If target is now empty, go to the root + [ -n "$1" ] || set -- / + + # Try to change into the determined directory + command cd -- "$@" +} -- cgit v1.2.3