Last active
March 5, 2020 14:05
-
-
Save lunix33/34d7395de996a5ff5ea7884269ecb19c to your computer and use it in GitHub Desktop.
Small function allowing to use `..` to go back a level. add a dot for each subsequent up. Simply source the file in bashrc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| ## | |
| # This script allow to use a shorthand to navigate the directory structure. | |
| # To use this script, simply source this script in your ~/.bashrc | |
| # | |
| # Examples: | |
| # `..` : Move up by 1 directory. | |
| # `....` : Move up by 3 directory. | |
| # `.../hello_world`: Move up by 2 directory, then move into the directory `hello_world`. | |
| ## | |
| shopt -s extdebug | |
| function _up() { | |
| # Only execute if the command starts with '..' | |
| if [ "${BASH_COMMAND:0:2}" == ".." ]; then | |
| # Tab completion refire the trap with the last command since it wasn't consumed. | |
| # Therefore this allows to consume the last command. | |
| [ "${BASH_COMMAND}" == "${_up_kill}" ] && \ | |
| _up_kill="" && \ | |
| return | |
| # Parse the command. | |
| precut=$(echo "${BASH_COMMAND}" | sed -E 's#^(\.*)\/?(.*)#\1;\2#') | |
| up=$(echo ${precut} | cut -d ';' -f1) | |
| postpath=$(echo ${precut} | cut -d ';' -f2) | |
| # Up based on the number of dot in the command. | |
| let "count = ${#up} - 2" | |
| for i in $(seq 0 ${count}); do | |
| cd .. | |
| done | |
| # Change directory to post up path | |
| [ "${postpath}" != "" ] && cd ${postpath} | |
| _up_kill="${BASH_COMMAND}" | |
| return 1 | |
| fi | |
| } | |
| trap '_up' DEBUG |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment