Linux bash 的目录书签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7374534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:08:24  来源:igfitidea点击:

Directory bookmarking for bash

linuxbashubuntu

提问by getmizanur

Is there any directory bookmarking utility for bash to allow move around faster on the command line?

是否有任何用于 bash 的目录书签实用程序以允许在命令行上更快地移动?

UPDATE

更新

Thanks guys for the feedback however I created my own simple shell script (feel free to modify/expand it)

感谢大家的反馈,但是我创建了自己的简单 shell 脚本(随意修改/扩展它)

function cdb() {
    USAGE="Usage: cdb [-c|-g|-d|-l] [bookmark]" ;
    if  [ ! -e ~/.cd_bookmarks ] ; then
        mkdir ~/.cd_bookmarks
    fi

    case  in
        # create bookmark
        -c) shift
            if [ ! -f ~/.cd_bookmarks/ ] ; then
                echo "cd `pwd`" > ~/.cd_bookmarks/"" ;
            else
                echo "Try again! Looks like there is already a bookmark ''"
            fi
            ;;
        # goto bookmark
        -g) shift
            if [ -f ~/.cd_bookmarks/ ] ; then 
                source ~/.cd_bookmarks/""
            else
                echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ;
            fi
            ;;
        # delete bookmark
        -d) shift
            if [ -f ~/.cd_bookmarks/ ] ; then 
                rm ~/.cd_bookmarks/"" ;
            else
                echo "Oops, forgot to specify the bookmark" ;
            fi    
            ;;
        # list bookmarks
        -l) shift
            ls -l ~/.cd_bookmarks/ ;
            ;;
         *) echo "$USAGE" ;
            ;;
    esac
}

INSTALL

安装

1./ create a file ~/.cdb and copy the above script into it.

1./ 创建一个文件 ~/.cdb 并将上面的脚本复制到其中。

2./ in your ~/.bashrc add the following

2./ 在您的 ~/.bashrc 中添加以下内容

if [ -f ~/.cdb ]; then
    source ~/.cdb
fi 

3./ restart your bash session

3./ 重启你的 bash 会话

USAGE

用法

1./ to create a bookmark

1./ 创建书签

$cd my_project
$cdb -c project1

2./ to goto a bookmark

2./ 转到书签

$cdb -g project1

3./ to list bookmarks

3./ 列出书签

$cdb -l 

4./ to delete a bookmark

4./删除书签

$cdb -d project1

5./ where are all my bookmarks stored?

5./ 我所有的书签都存储在哪里?

$cd ~/.cd_bookmarks

回答by ajreal

In bash script/command,
you can use pushdand popd

在 bash 脚本/命令中,
您可以使用pushdpopd

pushd

Save and then change the current directory. With no arguments, pushd exchanges the top two directories.

保存,然后更改当前目录。没有参数,pushd 交换前两个目录。

Usage

用法

cd /abc
pushd /xxx    <-- save /abc to environment variables and cd to /xxx
pushd /zzz
pushd +1      <-- cd /xxx

popdis to remove the variable (reverse manner)

popd就是去掉变量(逆向方式)

回答by Fredrik Pihl

Also, have a look at CDPATH

另外,看看CDPATH

A colon-separated list of search paths available to the cd command, similar in function to the $PATH variable for binaries. The $CDPATH variable may be set in the local ~/.bashrc file.

cd 命令可用的以冒号分隔的搜索路径列表,其功能类似于二进制文件的 $PATH 变量。$CDPATH 变量可以在本地 ~/.bashrc 文件中设置。

ash$ cd bash-doc
bash: cd: bash-doc: No such file or directory

bash$ CDPATH=/usr/share/doc
bash$ cd bash-doc
/usr/share/doc/bash-doc

bash$ echo $PWD
/usr/share/doc/bash-doc

and

cd -

It's the command-line equivalent of the back button (takes you to the previous directory you were in).

它是与后退按钮等效的命令行(将您带到您所在的上一个目录)。

回答by Fritz G. Mehner

bookmarks.shprovides a bookmark management system for the Bash version 4.0+. It can also use a Midnight Commander hotlist.

bookmarks.sh为 Bash 4.0+ 版本提供了一个书签管理系统。它还可以使用午夜指挥官热列表。

回答by Zied

Yes there is DirB: Directory Bookmarks for Bash well explained in this Linux Journalarticle

是的,有 DirB: Directory Bookmarks for Bash 在这篇Linux Journal文章中得到了很好的解释

An example from the article:

文章中的一个例子:

% cd ~/Desktop
% s d       # save(bookmark) ~/Desktop as d
% cd /tmp   # go somewhere
% pwd
/tmp
% g d       # go to the desktop
% pwd
/home/Desktop

回答by return42

Inspired by the question and answers here, I added the lines below to my ~/.bashrcfile.

受此处问题和答案的启发,我将以下几行添加到我的~/.bashrc文件中。

With this you have a favdircommand (function) to manage your favorites and a autocompletionfunction to select an item from these favorites.

有了这个,你就有了一个favdir命令(功能)来管理你的收藏夹和一个自动完成功能来从这些收藏夹中选择一个项目。

# ---------
# Favorites
# ---------

__favdirs_storage=~/.favdirs
__favdirs=( "$HOME" )

containsElement () {
    local e
    for e in "${@:2}"; do [[ "$e" == "" ]] && return 0; done
    return 1
}

function favdirs() {

    local cur
    local IFS
    local GLOBIGNORE

    case  in
        list)
            echo "favorite folders ..."
            printf -- ' - %s\n' "${__favdirs[@]}"
            ;;
        load)
            if [[ ! -e $__favdirs_storage ]] ; then
                favdirs save
            fi
            # mapfile requires bash 4 / my OS-X bash vers. is 3.2.53 (from 2007 !!?!).
            # mapfile -t __favdirs < $__favdirs_storage
            IFS=$'\r\n' GLOBIGNORE='*' __favdirs=($(< $__favdirs_storage))
            ;;
        save)
            printf -- '%s\n' "${__favdirs[@]}" > $__favdirs_storage
            ;;
        add)
            cur=${2-$(pwd)}
            favdirs load
            if containsElement "$cur" "${__favdirs[@]}" ; then
                echo "'$cur' allready exists in favorites"
            else
                __favdirs+=( "$cur" )
                favdirs save
                echo "'$cur' added to favorites"
            fi
            ;;
        del)
            cur=${2-$(pwd)}
            favdirs load
            local i=0
            for fav in ${__favdirs[@]}; do
                if [ "$fav" = "$cur" ]; then
                    echo "delete '$cur' from favorites"
                    unset __favdirs[$i]
                    favdirs save
                    break
                fi
                let i++
            done
            ;;
        *)
            echo "Manage favorite folders."
            echo ""
            echo "usage: favdirs [ list | load | save | add | del ]"
            echo ""
            echo "  list : list favorite folders"
            echo "  load : load favorite folders from $__favdirs_storage"
            echo "  save : save favorite directories to $__favdirs_storage"
            echo "  add  : add directory to favorites [default pwd $(pwd)]."
            echo "  del  : delete directory from favorites [default pwd $(pwd)]."
    esac
} && favdirs load

function __favdirs_compl_command() {
    COMPREPLY=( $( compgen -W "list load save add del" -- ${COMP_WORDS[COMP_CWORD]}))
} && complete -o default -F __favdirs_compl_command favdirs

function __favdirs_compl() {
    local IFS=$'\n'
    COMPREPLY=( $( compgen -W "${__favdirs[*]}" -- ${COMP_WORDS[COMP_CWORD]}))
}

alias _cd='cd'
complete -F __favdirs_compl _cd

Within the last two lines, an alias to change the current directory (with autocompletion) is created. With this alias (_cd) you are able to change to one of your favorite directories. May you wan't to change this alias to something which fits your needs.

在最后两行中,创建了一个用于更改当前目录(具有自动完成功能)的别名。使用此别名 ( _cd),您可以更改为您喜欢的目录之一。可能您不想将此别名更改为适合您需要的名称

With the function favdirsyou can manage your favorites (see usage).

使用该功能favdirs您可以管理您的收藏夹(见用法)。

$ favdirs 
Manage favorite folders.

usage: favdirs [ list | load | save | add | del ]

  list : list favorite folders
  load : load favorite folders from ~/.favdirs
  save : save favorite directories to ~/.favdirs
  add  : add directory to favorites [default pwd /tmp ].
  del  : delete directory from favorites [default pwd /tmp ].

回答by Dmitry Frank

Thanks for sharing your solution, and I'd like to share mine as well, which I find more useful than anything else I've came across before.

感谢您分享您的解决方案,我也想分享我的解决方案,我发现它比我以前遇到的任何其他方法都更有用。

The engine is a great, universal tool: command-line fuzzy finderby Junegunn.

该引擎是一个很棒的通用工具:Junegunn 的命令行模糊查找器

It primarily allows you to “fuzzy-find” files in a number of ways, but it also allows to feed arbitrary text data to it and filter this data. So, the shortcuts idea is simple: all we need is to maintain a file with paths (which are shortcuts), and fuzzy-filter this file. Here's how it looks: we type cdgcommand (from "cd global", if you like), get a list of our bookmarks, pick the needed one in just a few keystrokes, and press Enter. Working directory is changed to the picked item:

它主要允许您以多种方式“模糊查找”文件,但它也允许向其提供任意文本数据并过滤这些数据。所以,快捷方式的想法很简单:我们所需要的只是维护一个带有路径(即快捷方式)的文件,并对该文件进行模糊过滤。这是它的外观:我们输入cdg命令(来自“cd global”,如果您愿意),获取我们的书签列表,只需敲几下键就可以选择所需的书签,然后按 Enter。工作目录更改为选择的项目:

cdg

光盘

It is extremely fast and convenient: usually I just type 3-4 letters of the needed item, and all others are already filtered out. Additionally, of course we can move through list with arrow keys or with vim-like keybindings Ctrl+j/Ctrl+k.

它非常快速和方便:通常我只需输入所需项目的 3-4 个字母,其他的都已经过滤掉了。此外,当然我们可以使用箭头键或类似 vim 的键绑定Ctrl+j/在列表中移动Ctrl+k

Article with details: Fuzzy shortcuts for your shell.

带有详细信息的文章:shell 的模糊快捷方式

It is possible to use it for GUI applications as well (via xterm): I use that for my GUI file manager Double Commander. I have plans to write an article about this use case, too.

也可以将它用于 GUI 应用程序(通过 xterm):我将它用于我的 GUI 文件管理器Double Commander。我也计划写一篇关于这个用例的文章。

回答by Al Conrad

@getmizanur I used your cdb script. I enhanced it slightly by adding bookmarks tab completion. Here's my version of your cdb script.

@getmizanur 我使用了你的 cdb 脚本。我通过添加书签选项卡完成稍微增强了它。这是我的 cdb 脚本版本。

_cdb()
{
    local _script_commands=$(ls -1 ~/.cd_bookmarks/)
    local cur=${COMP_WORDS[COMP_CWORD]}

    COMPREPLY=( $(compgen -W "${_script_commands}" -- $cur) )
}
complete -F _cdb cdb


function cdb() {

    local USAGE="Usage: cdb [-h|-c|-d|-g|-l|-s] [bookmark]\n
    \t[-h or no args] - prints usage help\n
    \t[-c bookmark] - create bookmark\n
    \t[-d bookmark] - delete bookmark\n
    \t[-g bookmark] - goto bookmark\n
    \t[-l] - list bookmarks\n
    \t[-s bookmark] - show bookmark location\n
    \t[bookmark] - same as [-g bookmark]\n
    Press tab for bookmark completion.\n"        

    if  [ ! -e ~/.cd_bookmarks ] ; then
        mkdir ~/.cd_bookmarks
    fi

    case  in
        # create bookmark
        -c) shift
            if [ ! -f ~/.cd_bookmarks/ ] ; then
                echo "cd `pwd`" > ~/.cd_bookmarks/""
                complete -F _cdb cdb
            else
                echo "Try again! Looks like there is already a bookmark ''"
            fi
            ;;
        # goto bookmark
        -g) shift
            if [ -f ~/.cd_bookmarks/ ] ; then
                source ~/.cd_bookmarks/""
            else
                echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ;
            fi
            ;;
        # show bookmark
        -s) shift
            if [ -f ~/.cd_bookmarks/ ] ; then
                cat ~/.cd_bookmarks/""
            else
                echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ;
            fi
            ;;
        # delete bookmark
        -d) shift
            if [ -f ~/.cd_bookmarks/ ] ; then
                rm ~/.cd_bookmarks/"" ;
            else
                echo "Oops, forgot to specify the bookmark" ;
            fi
            ;;
        # list bookmarks
        -l) shift
            ls -1 ~/.cd_bookmarks/ ;
            ;;
        -h) echo -e $USAGE ;
            ;;
        # goto bookmark by default
        *)
            if [ -z "" ] ; then
                echo -e $USAGE
            elif [ -f ~/.cd_bookmarks/ ] ; then
                source ~/.cd_bookmarks/""
            else
                echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ;
            fi
            ;;
    esac
}

回答by tobimensch

Yes, one that I have written, that is called anc.

是的,我写过一个,叫做 anc。

https://github.com/tobimensch/anc

https://github.com/tobimensch/anc

Anc stands for anchor, but anc's anchors are really just bookmarks.

anc代表anchor,但是anc的anchors其实只是书签而已。

It's designed for ease of use and there're multiple ways of navigating, either by giving a text pattern, using numbers, interactively, by going back, or using [TAB] completion.

它旨在易于使用,并且有多种导航方式,可以通过提供文本模式、使用数字、交互方式、返回或使用 [TAB] 完成。

I'm actively working on it and open to input on how to make it better.

我正在积极致力于它,并愿意就如何改进它提供意见。

Allow me to paste the examples from anc's github page here:

请允许我将 anc 的 github 页面中的示例粘贴到此处:

# make the current directory the default anchor:
$ anc s

# go to /etc, then /, then /usr/local and then back to the default anchor:
$ cd /etc; cd ..; cd usr/local; anc

# go back to /usr/local :
$ anc b

# add another anchor:
$ anc a $HOME/test

# view the list of anchors (the default one has the asterisk):
$ anc l
(0) /path/to/first/anchor *
(1) /home/usr/test

# jump to the anchor we just added:
# by using its anchor number
$ anc 1
# or by jumping to the last anchor in the list
$ anc -1

# add multiple anchors:
$ anc a $HOME/projects/first $HOME/projects/second $HOME/documents/first

# use text matching to jump to $HOME/projects/first
$ anc pro fir

# use text matching to jump to $HOME/documents/first
$ anc doc fir

# add anchor and jump to it using an absolute path
$ anc /etc
# is the same as
$ anc a /etc; anc -1

# add anchor and jump to it using a relative path
$ anc ./X11 #note that "./" is required for relative paths
# is the same as
$ anc a X11; anc -1

# using wildcards you can add many anchors at once
$ anc a $HOME/projects/*

# use shell completion to see a list of matching anchors
# and select the one you want to jump to directly
$ anc pro[TAB]

回答by C?nh Toàn Nguy?n

Bashmarksis an amazingly simple and intuitive utility. In short, after installation, the usage is:

Bashmarks是一个非常简单和直观的实用程序。总之,安装后的用法是:

s <bookmark_name> - Saves the current directory as "bookmark_name"
g <bookmark_name> - Goes (cd) to the directory associated with "bookmark_name"
p <bookmark_name> - Prints the directory associated with "bookmark_name"
d <bookmark_name> - Deletes the bookmark
l                 - Lists all available bookmarks

回答by DerMike

For short term shortcuts, I have a the following in my respective init script (Sorry. I can't find the source right now and didn't bother then):

对于短期快捷方式,我在各自的 init 脚本中有以下内容(抱歉。我现在找不到源代码,当时也没有打扰):

function b() {
    alias ="cd `pwd -P`"
}

Usage:

用法:

In any directory that you want to bookmark type

在您要添加书签类型的任何目录中

b THEDIR # <THEDIR> being the name of your 'bookmark'

It will create an alias to cd (back) to here.

它将创建一个别名到 cd(返回)到这里。

To return to a 'bookmarked' dir type

返回“书签”目录类型

THEDIR

It will run the stored alias and cd back there.

它将运行存储的别名和 cd 回到那里。

Caution:Use only if you understand thatthis might override existing shell aliases and whatthat means.

注意:只有当您了解的是这可能会覆盖现有的shell别名和什么意思。