diff options
author | Tom Ryder <tom@sanctum.geek.nz> | 2015-05-29 14:55:07 +1200 |
---|---|---|
committer | Tom Ryder <tom@sanctum.geek.nz> | 2015-05-29 14:55:07 +1200 |
commit | cc743b7a924d2556b924b80df6682619b0aec010 (patch) | |
tree | 0e1d3bc915952dc34965a5607ee84fadba50be85 /bash/bashrc.d/ud.bash | |
parent | Sort .gitmodules (diff) | |
download | dotfiles-cc743b7a924d2556b924b80df6682619b0aec010.tar.gz dotfiles-cc743b7a924d2556b924b80df6682619b0aec010.zip |
Add ud() function as cd ../../../.. shortcut
Diffstat (limited to 'bash/bashrc.d/ud.bash')
-rw-r--r-- | bash/bashrc.d/ud.bash | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/bash/bashrc.d/ud.bash b/bash/bashrc.d/ud.bash new file mode 100644 index 00000000..c83b7c56 --- /dev/null +++ b/bash/bashrc.d/ud.bash @@ -0,0 +1,41 @@ +# Shortcut to step up the directory tree with an arbitrary number of steps, +# like cd .., cd ../.., etc +ud() { + + # Check and save optional first argument, number of steps upward; default + # to 1 if absent + local -i steps=${1:-1} + if ! ((steps > 0)) ; then + printf 'bash: %s: Invalid step count %s\n' "$FUNCNAME" "$1" >&2 + return 2 + fi + + # Check and save optional second argument, target directory; default to + # $PWD (typical usage case) + local dir=${2:-$PWD} + if [[ ! -e "$dir" ]] ; then + printf 'bash: %s: Target dir %s does not exist\n' "$FUNCNAME" "$2" >&2 + return 1 + fi + + # Append /.. to the target the specified number of times + local -i i + for (( i = 0 ; i < steps ; i++ )) ; do + dir=${dir%/}/.. + done + + # Try to change into it + cd -- "$dir" +} + +# Completion is only useful for the second argument +_ud() { + if ((COMP_CWORD == 2)) ; then + local word=${COMP_WORDS[COMP_CWORD]} + COMPREPLY=( $(compgen -A directory -- "$word" ) ) + else + return 1 + fi +} +complete -F _ud ud + |