bash使用像zsh这样的快捷方式扩展cd

前端之家收集整理的这篇文章主要介绍了bash使用像zsh这样的快捷方式扩展cd前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有可能在bash中扩展类似的东西

cd / u / lo / b<命中标签>

cd /usr/local / bin

对不起,我不能提前发布,我在工作,并且绑定功能比我最初想的更容易出问题.

这是我想出的:

绑定以下脚本:

  1. #!/bin/bash
  2. #$HOME/.bashrc.d/autocomplete.sh
  3. autocomplete_wrapper() {
  4. BASE="${READLINE_LINE% *} " #we save the line except for the last argument
  5. [[ "$BASE" == "$READLINE_LINE " ]] && BASE=""; #if the line has only 1 argument,we set the BASE to blank
  6. EXPANSION=($(autocomplete "${READLINE_LINE##* }"))
  7. [[ ${#EXPANSION[@]} -gt 1 ]] && echo "${EXPANSION[@]:1}" #if there is more than 1 match,we echo them
  8. READLINE_LINE="$BASE${EXPANSION[0]}" #the current line is now the base + the 1st element
  9. READLINE_POINT=${#READLINE_LINE} #we move our cursor at the end of the current line
  10. }
  11.  
  12. autocomplete() {
  13. LAST_CMD="$1"
  14. #Special starting character expansion for '~','./' and '/'
  15. [[ "${LAST_CMD:0:1}" == "~" ]] && LAST_CMD="$HOME${LAST_CMD:1}"
  16. S=1; [[ "${LAST_CMD:0:1}" == "/" || "${LAST_CMD:0:2}" == "./" ]] && S=2; #we don't expand those
  17.  
  18. #we do the path expansion of the last argument here by adding a * before each /
  19. EXPANSION=($(echo "$LAST_CMD*" | sed s:/:*/:"$S"g))
  20.  
  21. if [[ ! -e "${EXPANSION[0]}" ]];then #if the path cannot be expanded,we don't change the output
  22. echo "$LAST_CMD"
  23. elif [[ "${#EXPANSION[@]}" -eq 1 ]];then #else if there is only one match,we output it
  24. echo "${EXPANSION[0]}"
  25. else
  26. #else we expand the path as much as possible and return all the possible results
  27. while [[ $l -le "${#EXPANSION[0]}" ]]; do
  28. for i in "${EXPANSION[@]}"; do
  29. if [[ "${EXPANSION[0]:$l:1}" != "${i:$l:1}" ]]; then
  30. CTRL_LOOP=1
  31. break
  32. fi
  33. done
  34. [[ $CTRL_LOOP -eq 1 ]] && break
  35. ((l++))
  36. done
  37. #we add the partial solution at the beggining of the array of solutions
  38. echo "${EXPANSION[0]:0:$l} ${EXPANSION[@]}"
  39. fi
  40. }

使用以下命令:

  1. source "$HOME/.bashrc.d/autocomplete.sh"
  2. bind -x '"\t" : autocomplete_wrapper'

输出

  1. >$cd /u/lo/b<TAB>
  2. >$cd /usr/local/bin
  3.  
  4.  
  5. >$cd /u/l<TAB>
  6. /usr/local /usr/lib
  7. >$cd /usr/l

可以将绑定行添加到〜/ .bashrc文件中,执行以下操作:

  1. if [[ -s "$HOME/.bashrc.d/autocomplete.sh" ]]; then
  2. source "$HOME/.bashrc.d/autocomplete.sh"
  3. bind -x '"\t" : autocomplete_wrapper'
  4. fi

(摘自this answer)

此外,我强烈建议不要将此命令绑定到Tab键,因为它会覆盖默认的自动完成.

注意:在某些情况下,如果您尝试自动完成“/ path / with spaces / something”,则会出现错误,因为要完成的最后一个参数由${READLINE_LINE ## *}确定.如果在您的情况下这是一个问题,您应该编写一个函数,在考虑引号时返回行的最后一个参数

请随时要求进一步澄清,我欢迎任何改进此脚本的建议

猜你在找的Bash相关文章