Linux使用zsh提高效率的5条建议

2019-09-23 08:54:29刘景俊

现在你可以通过输入 d 来查看这个目录列表的前10个,然后用目录的序号来进行切换:

$ d
0    /usr/local
1    ~
2    /var/log
3    /var/opt
4    /usr/bin
5    /usr/lib
6    /tmp
7    ~/Projects/Opensource.com/zsh-5tips
8    ~/Projects
9    ~/Projects/ansible
$ pwd
/usr/local
$ 6
/tmp
$ pwd
/tmp

最后,你可以在 zsh 中利用 Tab 来自动补全目录名称。你可以先输入目录的首字母,然后按 TAB 键来补全它们:

$ pwd
/home/rgerardi
$ p/o/z (TAB)
$ Projects/Opensource.com/zsh-5tips/

以上仅仅是 zsh 强大的 Tab 补全系统中的一个功能。接来下我们来探索它更多的功能。

4、先进的 Tab 补全

zsh 强大的补全系统是它的卖点之一。为了简便起见,我称它为 Tab 补全,然而在系统底层,它起到了几个作用。这里通常包括展开以及命令补全,我会在这里用讨论它们。如果想了解更多,详见 用户手册。

在 Oh My Zsh 中,命令补全是默认启用的。要启用它,你只要在 .zshrc 文件中添加以下命令:

autoload -U compinit
compinit

zsh 的补全系统非常智能。它会尝试唯一提示可用在当前上下文环境中的项目 —— 比如,你输入了 cd 和 TAB,zsh 只会为你提示目录名,因为它知道其它的项目放在 cd 后面没用。

反之,如果你使用与用户相关的命令便会提示用户名,而 ssh 或者 ping 这类则会提示主机名。

zsh 拥有一个巨大而又完整的库,因此它能识别许多不同的命令。比如,如果你使用 tar 命令, 你可以按 TAB 键,它会为你展示一个可以用于解压的文件列表:

$ tar -xzvf test1.tar.gz test1/file1 (TAB)
file1 file2

如果使用 git 的话,这里有个更高级的示例。在这个示例中,当你按 TAB 键, zsh 会自动补全当前库可以操作的文件:

$ ls
original plan.txt zsh-5tips.md zsh_theme_small.png
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
 (use "git add <file>..." to update what will be committed)
 (use "git checkout -- <file>..." to discard changes in working directory)
    modified:  zsh-5tips.md
no changes added to commit (use "git add" and/or "git commit -a")
$ git add (TAB)
$ git add zsh-5tips.md

zsh 还能识别命令行选项,同时它只会提示与选中子命令相关的命令列表:

$ git commit - (TAB)
--all         -a    -- stage all modified and deleted paths
--allow-empty          -- allow recording an empty commit
--allow-empty-message      -- allow recording a commit with an empty message
--amend             -- amend the tip of the current branch
--author            -- override the author name used in the commit
--branch            -- show branch information
--cleanup            -- specify how the commit message should be cleaned up
--date             -- override the author date used in the commit
--dry-run            -- only show the list of paths that are to be committed or not, and any untracked
--edit         -e    -- edit the commit message before committing
--file         -F    -- read commit message from given file
--gpg-sign       -S    -- GPG-sign the commit
--include       -i    -- update the given files and commit the whole index
--interactive          -- interactively update paths in the index file
--message       -m    -- use the given message as the commit message
... TRUNCATED ...