cd -1, -2, -3 etc in Z shell

后端 未结 3 591
心在旅途
心在旅途 2021-01-31 04:58

How do you set up the Z shell such that typing cd - gives you a list of previously visited paths, and cd -1, -2, -3, etc. will then take you to the directories?

3条回答
  •  一个人的身影
    2021-01-31 05:31

    If you have setopt AUTO_PUSHD in your .zshrc then cd will automatically do a pushd of each directory you change to. Taking the example from ZyX:

    $ setopt AUTO_PUSHD
    $ mkdir -p 1/2/3/4
    $ cd 1
    $ cd 2
    $ cd 3
    $ cd 4
    

    You can see a list of the directories using dirs:

    $ dirs -v
    0    ~/1/2/3/4
    1    ~/1/2/3
    2    ~/1/2
    3    ~/1
    4    ~
    

    To be able to tab complete the list you can use the + and - arguments with cd ( meaning you hit the tab key):

    $ cd +
    1 -- ~/1/2/3
    2 -- ~/1/2
    3 -- ~/1
    4 -- ~
    

    Or the reverse:

    $ cd -
    0 -- ~
    1 -- ~/1
    2 -- ~/1/2
    3 -- ~/1/2/3
    

    Then just select the number to go to that directory:

    $ cd +2
    $ pwd
    ~/1/2
    

    Tab Complete Directories

    I always forget the magic sequence to do the following so I updated the answer to explain this part.

    The + and - will only take you to the directory, you can't tab complete the path in the stack (i.e. cd -2/ gives you nothing). To make this work, you can use a tilde (~).

    Make some directories in 3 to make this example better.

    $ mkdir 3/foo 3/bar 3/baz
    

    Then find the directory in the stack.

    $ cd ~+
    1 -- ~/1/2/3/4
    2 -- ~/1/2/3
    3 -- ~/1
    4 -- ~
    

    Then use tab completion on an entry.

    $ cd ~+2/
    4/    bar/  baz/  foo/
    

提交回复
热议问题