La utilidad de shell goto permite a los usuarios navegar a directorios con alias y también admite autocompletar.
Cómo funciona
Antes de poder usar goto, debes registrar tus alias de directorio. Por ejemplo:
1 |
goto -r dev /home/iridakos/development |
Luego cámbiate a ese directorio, por ejemplo:
1 |
goto dev |
Autocompletar en goto
goto viene con un buen script de autocompletar: cada vez que presionas la tecla Tab después del comando goto, Bash o Zsh te indicarán sugerencias de los alias disponibles:
1 2 3 4 |
$ goto <tab> bc /etc/bash_completion.d dev /home/iridakos/development rubies /home/iridakos/.rvm/rubies |
Instalar goto
Hay varias formas de instalar goto.
Vía script
Debes clonar el repositorio y ejecutar el script de instalación como superusuario o root:
1 2 3 |
git clone https://github.com/iridakos/goto.git cd goto sudo ./install |
Manualmente
Debes copiar el archivo goto.sh en algún lugar de tu sistema de archivos y agregar una línea en tu .zshrc o .bashrc para obtenerlo .
Por ejemplo, si colocaste el archivo en tu carpeta de inicio, todo lo que tienes que hacer es agregar la siguiente línea a tu archivo .zshrc o .bashrc:
1 |
source ~/goto.sh |
MacOS Homebrew
Una fórmula llamada goto está disponible para la shell Bash en MacOS:
1 |
brew install goto |
Añadir salida de color
1 |
echo -e "\$include /etc/inputrc\nset colored-completion-prefix on" >> ~/.inputrc |
Notas:
- Necesitas reiniciar tu shell después de la instalación.
- Debes tener la función de autocompletar de Bash habilitada para Bash en MacOS (consulta este problema).
- Puedes instalarla con brew install bash-complete si no la tienes habilitada.
Formas de usar goto
Cambiar a un directorio con alias
Para cambiar a un directorio con alias, escribe:
1 |
goto <alias> |
Por ejemplo:
1 |
goto dev |
Registrar un alias
Para registrar un alias de directorio, debes escribir:
1 |
goto -r <alias> <directory> |
O
1 |
goto --register <alias> <directory> |
Por ejemplo:
1 |
goto -r blog /mnt/external/projects/html/blog |
O
1 |
goto --register blog /mnt/external/projects/html/blog |
Notas:
- goto expande los directorios, por lo que puedes asignar fácilmente un alias a tu directorio actual. Hazlo con el siguiente comando y se asignará automáticamente a toda la ruta:
1goto -r last_release . - Al presionar la tecla Tab después del nombre de alias se proporcionan las sugerencias de directorio predeterminadas de la shell.
Anular el registro de un alias
Para cancelar el registro de un alias, debes usar:
1 |
goto -u <alias> |
O
1 |
goto --unregister <alias> |
Por ejemplo:
1 |
goto -u last_release |
O
1 |
goto --unregister last_release |
Nota: Al presionar la tecla Tab después del comando (-u o –unregister), el script te pedirá la lista de alias registrados.
Lista de alias
Para obtener una lista de tus alias registrados actualmente, tienes que usar:
1 |
goto -l |
O
1 |
goto --list |
Expandir un alias
Para expandir un alias a su valor, utiliza:
1 |
goto -x <alias> |
O
1 |
goto --expand <alias> |
Por ejemplo:
1 |
goto -x last_release |
O
1 |
goto --expand last_release |
Limpiar alias
Para limpiar los alias de directorios que ya no son accesibles en tu sistema de archivos, debes usar:
1 |
goto -c |
O
1 |
goto --cleanup |
Obtener ayuda
Para ver la información de ayuda de la herramienta, debes utilizar:
1 |
goto -h |
O
1 |
goto --help |
Ver la versión
Para ver la versión de la herramienta, debes utilizar:
1 |
goto -v |
O
1 |
goto --version |
Insertar antes de cambiar directorios
Para insertar el directorio actual en el conjunto de directorios antes de cambiar los directorios, escribe:
1 |
goto -p <alias> |
O
1 |
goto --push <alias> |
Revertir a un directorio insertado
Para volver a un directorio insertado, escribe:
1 |
goto -o |
O
1 |
goto --pop |
Solución de problemas
Si ves el error command not found: compdef en Zsh, significa que necesitas cargar bashcompinit. Para hacerlo, agrega esto a tu archivo .zshrc:
1 2 |
autoload bashcompinit bashcompinit |
Involúcrate
La herramienta goto es de código abierto bajo los términos de la licencia MIT, y las contribuciones son bienvenidas. Para obtener más información, debes visitar la sección Contribución en el repositorio GitHub de goto.
Script de goto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
goto() { local target _goto_resolve_db if [ -z "$1" ]; then # display usage and exit when no args _goto_usage return fi subcommand="$1" shift case "$subcommand" in -c|--cleanup) _goto_cleanup "$@" ;; -r|--register) # Register an alias _goto_register_alias "$@" ;; -u|--unregister) # Unregister an alias _goto_unregister_alias "$@" ;; -p|--push) # Push the current directory onto the pushd stack, then goto _goto_directory_push "$@" ;; -o|--pop) # Pop the top directory off of the pushd stack, then change that directory _goto_directory_pop ;; -l|--list) _goto_list_aliases ;; -x|--expand) # Expand an alias _goto_expand_alias "$@" ;; -h|--help) _goto_usage ;; -v|--version) _goto_version ;; *) _goto_directory "$subcommand" ;; esac return $? } _goto_resolve_db() { GOTO_DB="${GOTO_DB:-$HOME/.goto}" touch -a "$GOTO_DB" } _goto_usage() { cat <<\USAGE usage: goto [<option>] <alias> [<directory>] default usage: goto <alias> - changes to the directory registered for the given alias OPTIONS: -r, --register: registers an alias goto -r|--register <alias> <directory> -u, --unregister: unregisters an alias goto -u|--unregister <alias> -p, --push: pushes the current directory onto the stack, then performs goto goto -p|--push <alias> -o, --pop: pops the top directory from the stack, then changes to that directory goto -o|--pop -l, --list: lists aliases goto -l|--list -x, --expand: expands an alias goto -x|--expand <alias> -c, --cleanup: cleans up non existent directory aliases goto -c|--cleanup -h, --help: prints this help goto -h|--help -v, --version: displays the version of the goto script goto -v|--version USAGE } # Displays version _goto_version() { echo "goto version 1.2.4.1" } # Expands directory. # Helpful for ~, ., .. paths _goto_expand_directory() { builtin cd "$1" 2>/dev/null && pwd } # Lists registered aliases. _goto_list_aliases() { local IFS=$' ' if [ -f "$GOTO_DB" ]; then while read -r name directory; do printf '\e[1;36m%20s \e[0m%s\n' "$name" "$directory" done < "$GOTO_DB" else echo "You haven't configured any directory aliases yet." fi } # Expands a registered alias. _goto_expand_alias() { if [ "$#" -ne "1" ]; then _goto_error "usage: goto -x|--expand <alias>" return fi local resolved resolved=$(_goto_find_alias_directory "$1") if [ -z "$resolved" ]; then _goto_error "alias '$1' does not exist" return fi echo "$resolved" } # Lists duplicate directory aliases _goto_find_duplicate() { local duplicates= duplicates=$(sed -n 's:[^ ]* '"$1"'$:&:p' "$GOTO_DB" 2>/dev/null) echo "$duplicates" } # Registers and alias. _goto_register_alias() { if [ "$#" -ne "2" ]; then _goto_error "usage: goto -r|--register <alias> <directory>" return 1 fi if ! [[ $1 =~ ^[[:alnum:]]+[a-zA-Z0-9_-]*$ ]]; then _goto_error "invalid alias - can start with letters or digits followed by letters, digits, hyphens or underscores" return 1 fi local resolved resolved=$(_goto_find_alias_directory "$1") if [ -n "$resolved" ]; then _goto_error "alias '$1' exists" return 1 fi local directory directory=$(_goto_expand_directory "$2") if [ -z "$directory" ]; then _goto_error "failed to register '$1' to '$2' - can't cd to directory" return 1 fi local duplicate duplicate=$(_goto_find_duplicate "$directory") if [ -n "$duplicate" ]; then _goto_warning "duplicate alias(es) found: \\n$duplicate" fi # Append entry to file. echo "$1 $directory" >> "$GOTO_DB" echo "Alias '$1' registered successfully." } # Unregisters the given alias. _goto_unregister_alias() { if [ "$#" -ne "1" ]; then _goto_error "usage: goto -u|--unregister <alias>" return 1 fi local resolved resolved=$(_goto_find_alias_directory "$1") if [ -z "$resolved" ]; then _goto_error "alias '$1' does not exist" return 1 fi # shellcheck disable=SC2034 local readonly GOTO_DB_TMP="$HOME/.goto_" # Delete entry from file. sed "/^$1 /d" "$GOTO_DB" > "$GOTO_DB_TMP" && mv "$GOTO_DB_TMP" "$GOTO_DB" echo "Alias '$1' unregistered successfully." } # Pushes the current directory onto the stack, then goto _goto_directory_push() { if [ "$#" -ne "1" ]; then _goto_error "usage: goto -p|--push <alias>" return fi { pushd . || return; } 1>/dev/null 2>&1 _goto_directory "$@" } # Pops the top directory from the stack, then goto _goto_directory_pop() { { popd || return; } 1>/dev/null 2>&1 } # Unregisters aliases whose directories no longer exist. _goto_cleanup() { if ! [ -f "$GOTO_DB" ]; then return fi while IFS= read -r i && [ -n "$i" ]; do echo "Cleaning up: $i" _goto_unregister_alias "$i" done <<< "$(awk '{al=$1; $1=""; dir=substr($0,2); system("[ ! -d \"" dir "\" ] && echo " al)}' "$GOTO_DB")" } # Changes to the given alias' directory _goto_directory() { local target target=$(_goto_resolve_alias "$1") || return 1 builtin cd "$target" 2> /dev/null || \ { _goto_error "Failed to goto '$target'" && return 1; } } # Fetches the alias directory. _goto_find_alias_directory() { local resolved resolved=$(sed -n "s/^$1 \\(.*\\)/\\1/p" "$GOTO_DB" 2>/dev/null) echo "$resolved" } # Displays the given error. # Used for common error output. _goto_error() { (>&2 echo -e "goto error: $1") } # Displays the given warning. # Used for common warning output. _goto_warning() { (>&2 echo -e "goto warning: $1") } # Displays entries with aliases starting as the given one. _goto_print_similar() { local similar similar=$(sed -n "/^$1[^ ]* .*/p" "$GOTO_DB" 2>/dev/null) if [ -n "$similar" ]; then (>&2 echo "Did you mean:") (>&2 column -t <<< "$similar") fi } # Fetches alias directory, errors if it doesn't exist. _goto_resolve_alias() { local resolved resolved=$(_goto_find_alias_directory "$1") if [ -z "$resolved" ]; then _goto_error "unregistered alias $1" _goto_print_similar "$1" return 1 else echo "${resolved}" fi } # Completes the goto function with the available commands _complete_goto_commands() { local IFS=$' \t\n' # shellcheck disable=SC2207 COMPREPLY=($(compgen -W "-r --register -u --unregister -p --push -o --pop -l --list -x --expand -c --cleanup -v --version" -- "$1")) } # Completes the goto function with the available aliases _complete_goto_aliases() { local IFS=$'\n' matches _goto_resolve_db # shellcheck disable=SC2207 matches=($(sed -n "/^$1/p" "$GOTO_DB" 2>/dev/null)) if [ "${#matches[@]}" -eq "1" ]; then # remove the filenames attribute from the completion method compopt +o filenames 2>/dev/null # if you find only one alias don't append the directory COMPREPLY=("${matches[0]// *}") else for i in "${!matches[@]}"; do # remove the filenames attribute from the completion method compopt +o filenames 2>/dev/null if ! [[ $(uname -s) =~ Darwin* ]]; then matches[$i]=$(printf '%*s' "-$COLUMNS" "${matches[$i]}") COMPREPLY+=("$(compgen -W "${matches[$i]}")") else COMPREPLY+=("${matches[$i]// */}") fi done fi } # Bash programmable completion for the goto function _complete_goto_bash() { local cur="${COMP_WORDS[$COMP_CWORD]}" prev if [ "$COMP_CWORD" -eq "1" ]; then # if we are on the first argument if [[ $cur == -* ]]; then # and starts like a command, prompt commands _complete_goto_commands "$cur" else # and doesn't start as a command, prompt aliases _complete_goto_aliases "$cur" fi elif [ "$COMP_CWORD" -eq "2" ]; then # if we are on the second argument prev="${COMP_WORDS[1]}" if [[ $prev = "-u" ]] || [[ $prev = "--unregister" ]]; then # prompt with aliases if user tries to unregister one _complete_goto_aliases "$cur" elif [[ $prev = "-x" ]] || [[ $prev = "--expand" ]]; then # prompt with aliases if user tries to expand one _complete_goto_aliases "$cur" elif [[ $prev = "-p" ]] || [[ $prev = "--push" ]]; then # prompt with aliases only if user tries to push _complete_goto_aliases "$cur" fi elif [ "$COMP_CWORD" -eq "3" ]; then # if we are on the third argument prev="${COMP_WORDS[1]}" if [[ $prev = "-r" ]] || [[ $prev = "--register" ]]; then # prompt with directories only if user tries to register an alias local IFS=$' \t\n' # shellcheck disable=SC2207 COMPREPLY=($(compgen -d -- "$cur")) fi fi } # Zsh programmable completion for the goto function _complete_goto_zsh() { local all_aliases=() while IFS= read -r line; do all_aliases+=("$line") done <<< "$(sed -e 's/ /:/g' ~/.goto 2>/dev/null)" local state local -a options=( '(1)'{-r,--register}'[registers an alias]:register:->register' '(- 1 2)'{-u,--unregister}'[unregisters an alias]:unregister:->unregister' '(: -)'{-l,--list}'[lists aliases]' '(*)'{-c,--cleanup}'[cleans up non existent directory aliases]' '(1 2)'{-x,--expand}'[expands an alias]:expand:->aliases' '(1 2)'{-p,--push}'[pushes the current directory onto the stack, then performs goto]:push:->aliases' '(*)'{-o,--pop}'[pops the top directory from stack, then changes to that directory]' '(: -)'{-h,--help}'[prints this help]' '(* -)'{-v,--version}'[displays the version of the goto script]' ) _arguments -C \ "${options[@]}" \ '1:alias:->aliases' \ '2:dir:_files' \ && ret=0 case ${state} in (aliases) _describe -t aliases 'goto aliases:' all_aliases && ret=0 ;; (unregister) _describe -t aliases 'unregister alias:' all_aliases && ret=0 ;; esac return $ret } goto_aliases=($(alias | sed -n "s/.*\s\(.*\)='goto'/\1/p")) goto_aliases+=("goto") for i in "${goto_aliases[@]}" do # Register the goto completions. if [ -n "${BASH_VERSION}" ]; then if ! [[ $(uname -s) =~ Darwin* ]]; then complete -o filenames -F _complete_goto_bash $i else complete -F _complete_goto_bash $i fi elif [ -n "${ZSH_VERSION}" ]; then compdef _complete_goto_zsh $i else echo "Unsupported shell." exit 1 fi done |