项目的其他语言版本
Čeština ∙ Deutsch ∙ Ελληνικά ∙ English ∙ Español ∙ Français ∙ Indonesia ∙ Italiano ∙ 日本語 ∙ 한국어 ∙ polski ∙ Português ∙ Română ∙ Русский ∙ Slovenščina ∙ Українська ∙ 简体中文 ∙ 繁體中文
Note: I’m planning to revise this and looking for a new co-author to help with expanding this into a more comprehensive guide. While it’s very popular, it could be broader and a bit deeper. If you like to write and are close to being an expert on this material and willing to consider helping, please drop me a note at josh (0x40) holloway.com. –jlevy, Holloway. Thank you!

Fluency on the command line is a skill often neglected or considered arcane, but it improves your flexibility and productivity as an engineer in both obvious and subtle ways. This is a selection of notes and tips on using the command-line that we’ve found useful when working on Linux. Some tips are elementary, and some are fairly specific, sophisticated, or obscure. This page is not long, but if you can use and recall all the items here, you know a lot.
熟练使用命令行是一种常常被忽视,或被认为难以掌握的技能,但实际上,它会提高你作为工程师的灵活性以及生产力。本文是一份我在 Linux 上工作时,发现的一些命令行使用技巧的摘要。有些技巧非常基础,而另一些则相当复杂,甚至晦涩难懂。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。
This work is the result of many authors and translators. Some of this originally appeared on Quora, but it has since moved to GitHub, where people more talented than the original author have made numerous improvements. Please submit a question if you have a question related to the command line. Please contribute if you see an error or something that could be better!
Meta前言
Scope:
涵盖范围:
-
This guide is for both beginners and experienced users. The goals are breadth (everything important), specificity (give concrete examples of the most common case), and brevity (avoid things that aren’t essential or digressions you can easily look up elsewhere). Every tip is essential in some situation or significantly saves time over alternatives.
这篇文章不仅能帮助刚接触命令行的新手,而且对具有经验的人也大有裨益。本文致力于做到覆盖面广(涉及所有重要的内容),具体(给出具体的最常用的例子),以及简洁(避免冗余的内容,或是可以在其他地方轻松查到的细枝末节)。在特定应用场景下,本文的内容属于基本功或者能帮助您节约大量的时间。
-
This is written for Linux, with the exception of the “macOS only” and “Windows only” sections. Many of the other items apply or can be installed on other Unices or macOS (or even Cygwin).
本文主要为 Linux 所写,但在仅限 OS X 系统章节和仅限 Windows 系统章节中也包含有对应操作系统的内容。除去这两个章节外,其它的内容大部分均可在其他类 Unix 系统或 OS X,甚至 Cygwin 中得到应用。
-
The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting.
本文主要关注于交互式 Bash,但也有很多技巧可以应用于其他 shell 和 Bash 脚本当中。
-
It includes both “standard” Unix commands as well as ones that require special package installs — so long as they are important enough to merit inclusion.
除去“标准的”Unix 命令,本文还包括了一些依赖于特定软件包的命令(前提是它们具有足够的价值)。
Notes:
注意事项:
-
To keep this to one page, content is implicitly included by reference. You’re smart enough to look up more detail elsewhere once you know the idea or command to Google. Use
apt,yum,dnf,pacman,piporbrew(as appropriate) to install new programs.为了能在一页内展示尽量多的东西,一些具体的信息可以在引用的页面中找到。我们相信机智的你知道如何使用 Google 或者其他搜索引擎来查阅到更多的详细信息。文中部分命令需要您使用
apt-get,yum,dnf,pacman,pip或brew(以及其它合适的包管理器)来安装依赖的程序。 -
Use Explainshell to get a helpful breakdown of what commands, options, pipes etc. do.
遇到问题的话,请尝试使用 Explainshell 去获取相关命令、参数、管道等内容的解释。
Basics基础
-
Learn basic Bash. Actually, type
man bashand at least skim the whole thing; it’s pretty easy to follow and not that long. Alternate shells can be nice, but Bash is powerful and always available (learning only zsh, fish, etc., while tempting on your own laptop, restricts you in many situations, such as using existing servers).学习 Bash 的基础知识。具体地,在命令行中输入
man bash并至少全文浏览一遍; 它理解起来很简单并且不冗长。其他的 shell 可能很好用,但 Bash 的功能已经足够强大并且到几乎总是可用的( 如果你只学习 zsh,fish 或其他的 shell 的话,在你自己的设备上会显得很方便,但过度依赖这些功能会给您带来不便,例如当你需要在服务器上工作时)。 -
Learn at least one text-based editor well. The
nanoeditor is one of the simplest for basic editing (opening, editing, saving, searching). However, for the power user in a text terminal, there is no substitute for Vim (vi), the hard-to-learn but venerable, fast, and full-featured editor. Many people also use the classic Emacs, particularly for larger editing tasks. (Of course, any modern software developer working on an extensive project is unlikely to use only a pure text-based editor and should also be familiar with modern graphical IDEs and tools.)熟悉至少一个基于文本的编辑器。通常而言 Vim (
vi) 会是你最好的选择,毕竟在终端中编辑文本时 Vim 是最好用的工具(甚至大部分情况下 Vim 要比 Emacs、大型 IDE 或是炫酷的编辑器更好用)。 -
Finding documentation:
- Know how to read official documentation with
man(for the inquisitive,man manlists the section numbers, e.g. 1 is “regular” commands, 5 is files/conventions, and 8 are for administration). Find man pages withapropos. - Know that some commands are not executables, but Bash builtins, and that you can get help on them with
helpandhelp -d. You can find out whether a command is an executable, shell builtin or an alias by usingtype command. curl cheat.sh/commandwill give a brief “cheat sheet” with common examples of how to use a shell command.
学会如何使用
man命令去阅读文档。学会使用apropos去查找文档。知道有些命令并不对应可执行文件,而是在 Bash 内置好的,此时可以使用help和help -d命令获取帮助信息。你可以用type 命令来判断这个命令到底是可执行文件、shell 内置命令还是别名。 - Know how to read official documentation with
-
Learn about redirection of output and input using
>and<and pipes using|. Know>overwrites the output file and>>appends. Learn about stdout and stderr.学会使用
>和<来重定向输出和输入,学会使用|来重定向管道。明白>会覆盖了输出文件而>>是在文件末添加。了解标准输出 stdout 和标准错误 stderr。 -
Learn about file glob expansion with
*(and perhaps?and[…]) and quoting and the difference between double"and single'quotes. (See more on variable expansion below.)学会使用通配符
*(或许再算上?和[…]) 和引用以及引用中'和"的区别(后文中有一些具体的例子)。 -
Be familiar with Bash job management:
&, ctrl-z, ctrl-c,jobs,fg,bg,kill, etc.熟悉 Bash 中的任务管理工具:
&,ctrl-z,ctrl-c,jobs,fg,bg,kill等。 -
Know
ssh, and the basics of passwordless authentication, viassh-agent,ssh-add, etc.学会使用
ssh进行远程命令行登录,最好知道如何使用ssh-agent,ssh-add等命令来实现基础的无密码认证登录。 -
Basic file management:
lsandls -l(in particular, learn what every column inls -lmeans),less,head,tailandtail -f(or even better,less +F),lnandln -s(learn the differences and advantages of hard versus soft links),chown,chmod,du(for a quick summary of disk usage:du -hs *). For filesystem management,df,mount,fdisk,mkfs,lsblk. Learn what an inode is (ls -iordf -i).学会基本的文件管理工具:
ls和ls -l(了解ls -l中每一列代表的意义),less,head,tail和tail -f(甚至less +F),ln和ln -s(了解硬链接与软链接的区别),chown,chmod,du(硬盘使用情况概述:du -hs *)。 关于文件系统的管理,学习df,mount,fdisk,mkfs,lsblk。知道 inode 是什么(与ls -i和df -i等命令相关)。 -
Basic network management:
iporifconfig,dig,traceroute,route.学习基本的网络管理工具:
ip或ifconfig,dig。 -
Learn and use a version control management system, such as
git.学习并使用一种版本控制管理系统,例如
git。 -
Know regular expressions well, and the various flags to
grep/egrep. The-i,-o,-v,-A,-B, and-Coptions are worth knowing.熟悉正则表达式,学会使用
grep/egrep,它们的参数中-i,-o,-v,-A,-B和-C这些是很常用并值得认真学习的。 -
Learn to use
apt-get,yum,dnforpacman(depending on distro) to find and install packages. And make sure you havepipto install Python-based command-line tools (a few below are easiest to install viapip).学会使用
apt-get,yum,dnf或pacman(具体使用哪个取决于你使用的 Linux 发行版)来查找和安装软件包。并确保你的环境中有pip来安装基于 Python 的命令行工具 (接下来提到的部分程序使用pip来安装会很方便)。
Everyday use日常使用
-
In Bash, use Tab to complete arguments or list all available commands and ctrl-r to search through command history (after pressing, type to search, press ctrl-r repeatedly to cycle through more matches, press Enter to execute the found command, or hit the right arrow to put the result in the current line to allow editing).
在 Bash 中,可以通过按 Tab 键实现自动补全参数,使用 ctrl-r 搜索命令行历史记录(按下按键之后,输入关键字便可以搜索,重复按下 ctrl-r 会向后查找匹配项,按下 Enter 键会执行当前匹配的命令,而按下右方向键会将匹配项放入当前行中,不会直接执行,以便做出修改)。
-
In Bash, use ctrl-w to delete the last word, and ctrl-u to delete the content from current cursor back to the start of the line. Use alt-b and alt-f to move by word, ctrl-a to move cursor to beginning of line, ctrl-e to move cursor to end of line, ctrl-k to kill to the end of the line, ctrl-l to clear the screen. See
man readlinefor all the default keybindings in Bash. There are a lot. For example alt-. cycles through previous arguments, and alt-* expands a glob.在 Bash 中,可以按下 ctrl-w 删除你键入的最后一个单词,ctrl-u 可以删除行内光标所在位置之前的内容,alt-b 和 alt-f 可以以单词为单位移动光标,ctrl-a 可以将光标移至行首,ctrl-e 可以将光标移至行尾,ctrl-k 可以删除光标至行尾的所有内容,ctrl-l 可以清屏。键入
man readline可以查看 Bash 中的默认快捷键。内容有很多,例如 alt-. 循环地移向前一个参数,而 alt-* 可以展开通配符。 -
Alternatively, if you love vi-style key-bindings, use
set -o vi(andset -o emacsto put it back).你喜欢的话,可以执行
set -o vi来使用 vi 风格的快捷键,而执行set -o emacs可以把它改回来。 -
For editing long commands, after setting your editor (for example
export EDITOR=vim), ctrl-x ctrl-e will open the current command in an editor for multi-line editing. Or in vi style, escape-v.为了便于编辑长命令,在设置你的默认编辑器后(例如
export EDITOR=vim),ctrl-x ctrl-e 会打开一个编辑器来编辑当前输入的命令。在 vi 风格下快捷键则是 escape-v。 -
To see recent commands, use
history. Follow with!n(wherenis the command number) to execute again. There are also many abbreviations you can use, the most useful probably being!$for last argument and!!for last command (see “HISTORY EXPANSION” in the man page). However, these are often easily replaced with ctrl-r and alt-..键入
history查看命令行历史记录,再用!n(n是命令编号)就可以再次执行。其中有许多缩写,最有用的大概就是!$, 它用于指代上次键入的参数,而!!可以指代上次键入的命令了(参考 man 页面中的“HISTORY EXPANSION”)。不过这些功能,你也可以通过快捷键 ctrl-r 和 alt-. 来实现。 -
Go to your home directory with
cd. Access files relative to your home directory with the~prefix (e.g.~/.bashrc). Inshscripts refer to the home directory as$HOME.cd命令可以切换工作路径,输入cd ~可以进入 home 目录。要访问你的 home 目录中的文件,可以使用前缀~(例如~/.bashrc)。在sh脚本里则用环境变量$HOME指代 home 目录的路径。 -
To go back to the previous working directory:
cd -.回到前一个工作路径:
cd -。 -
If you are halfway through typing a command but change your mind, hit alt-# to add a
#at the beginning and enter it as a comment (or use ctrl-a, #, enter). You can then return to it later via command history.如果你输入命令的时候中途改了主意,按下 alt-# 在行首添加
#把它当做注释再按下回车执行(或者依次按下 ctrl-a, #, enter)。这样做的话,之后借助命令行历史记录,你可以很方便恢复你刚才输入到一半的命令。 -
Use
xargs(orparallel). It’s very powerful. Note you can control how many items execute per line (-L) as well as parallelism (-P). If you’re not sure if it’ll do the right thing, usexargs echofirst. Also,-I{}is handy. Examples:使用
xargs( 或parallel)。他们非常给力。注意到你可以控制每行参数个数(-L)和最大并行数(-P)。如果你不确定它们是否会按你想的那样工作,先使用xargs echo查看一下。此外,使用-I{}会很方便。例如:
find . -name '*.py' | xargs grep some_function
cat hosts | xargs -I{} ssh root@{} hostname
-
pstree -pis a helpful display of the process tree.pstree -p以一种优雅的方式展示进程树。 -
Use
pgrepandpkillto find or signal processes by name (-fis helpful).使用
pgrep和pkill根据名字查找进程或发送信号(-f参数通常有用)。 -
Know the various signals you can send processes. For example, to suspend a process, use
kill -STOP [pid]. For the full list, seeman 7 signal了解你可以发往进程的信号的种类。比如,使用
kill -STOP [pid]停止一个进程。使用man 7 signal查看详细列表。 -
Use
nohupordisownif you want a background process to keep running forever.使用
nohup或disown使一个后台进程持续运行。 -
Check what processes are listening via
netstat -lntporss -plat(for TCP; add-ufor UDP) orlsof -iTCP -sTCP:LISTEN -P -n(which also works on macOS).使用
netstat -lntp或ss -plat检查哪些进程在监听端口(默认是检查 TCP 端口; 添加参数-u则检查 UDP 端口)或者lsof -iTCP -sTCP:LISTEN -P -n(这也可以在 OS X 上运行)。 -
See also
lsofandfuserfor open sockets and files.lsof来查看开启的套接字和文件。 -
See
uptimeorwto know how long the system has been running.使用
uptime或w来查看系统已经运行多长时间。 -
Use
aliasto create shortcuts for commonly used commands. For example,alias ll='ls -latr'creates a new aliasll.使用
alias来创建常用命令的快捷形式。例如:alias ll='ls -latr'创建了一个新的命令别名ll。 -
Save aliases, shell settings, and functions you commonly use in
~/.bashrc, and arrange for login shells to source it. This will make your setup available in all your shell sessions.可以把别名、shell 选项和常用函数保存在
~/.bashrc,具体看下这篇文章。这样做的话你就可以在所有 shell 会话中使用你的设定。 -
Put the settings of environment variables as well as commands that should be executed when you login in
~/.bash_profile. Separate configuration will be needed for shells you launch from graphical environment logins andcronjobs.把环境变量的设定以及登陆时要执行的命令保存在
~/.bash_profile。而对于从图形界面启动的 shell 和cron启动的 shell,则需要单独配置文件。 -
Synchronize your configuration files (e.g.
.bashrcand.bash_profile) among various computers with Git.要想在几台电脑中同步你的配置文件(例如
.bashrc和.bash_profile),可以借助 Git。 -
Understand that care is needed when variables and filenames include whitespace. Surround your Bash variables with quotes, e.g.
"$FOO". Prefer the-0or-print0options to enable null characters to delimit filenames, e.g.locate -0 pattern | xargs -0 ls -alorfind / -print0 -type d | xargs -0 ls -al. To iterate on filenames containing whitespace in a for loop, set your IFS to be a newline only usingIFS=$'\n'.当变量和文件名中包含空格的时候要格外小心。Bash 变量要用引号括起来,比如
"$FOO"。尽量使用-0或-print0选项以便用 NULL 来分隔文件名,例如locate -0 pattern | xargs -0 ls -al或find / -print0 -type d | xargs -0 ls -al。如果 for 循环中循环访问的文件名含有空字符(空格、tab 等字符),只需用IFS=$'\n'把内部字段分隔符设为换行符。 -
In Bash scripts, use
set -x(or the variantset -v, which logs raw input, including unexpanded variables and comments) for debugging output. Use strict modes unless you have a good reason not to: Useset -eto abort on errors (nonzero exit code). Useset -uto detect unset variable usages. Considerset -o pipefailtoo, to abort on errors within pipes (though read up on it more if you do, as this topic is a bit subtle). For more involved scripts, also usetrapon EXIT or ERR. A useful habit is to start a script like this, which will make it detect and abort on common errors and print a message:在 Bash 脚本中,使用
set -x去调试输出(或者使用它的变体set -v,它会记录原始输入,包括多余的参数和注释)。尽可能地使用严格模式:使用set -e令脚本在发生错误时退出而不是继续运行;使用set -u来检查是否使用了未赋值的变量;试试set -o pipefail,它可以监测管道中的错误。当牵扯到很多脚本时,使用trap来检测 ERR 和 EXIT。一个好的习惯是在脚本文件开头这样写,这会使它能够检测一些错误,并在错误发生时中断程序并输出信息:
set -euo pipefail
trap "echo 'error: Script failed: see failed command above'" ERR
-
In Bash scripts, subshells (written with parentheses) are convenient ways to group commands. A common example is to temporarily move to a different working directory, e.g.
在 Bash 脚本中,子 shell(使用括号
(...))是一种组织参数的便捷方式。一个常见的例子是临时地移动工作路径,代码如下:
# do something in current dir
(cd /some/other/dir && other-command)
# continue in original dir
-
In Bash, note there are lots of kinds of variable expansion. Checking a variable exists:
${name:?error message}. For example, if a Bash script requires a single argument, just writeinput_file=${1:?usage: $0 input_file}. Using a default value if a variable is empty:${name:-default}. If you want to have an additional (optional) parameter added to the previous example, you can use something likeoutput_file=${2:-logfile}. If$2is omitted and thus empty,output_filewill be set tologfile. Arithmetic expansion:i=$(( (i + 1) % 5 )). Sequences:{1..10}. Trimming of strings:${var%suffix}and${var#prefix}. For example ifvar=foo.pdf, thenecho ${var%.pdf}.txtprintsfoo.txt.在 Bash 中,变量有许多的扩展方式。
${name:?error message}用于检查变量是否存在。此外,当 Bash 脚本只需要一个参数时,可以使用这样的代码input_file=${1:?usage: $0 input_file}。在变量为空时使用默认值:${name:-default}。如果你要在之前的例子中再加一个(可选的)参数,可以使用类似这样的代码output_file=${2:-logfile},如果省略了$2,它的值就为空,于是output_file就会被设为logfile。数学表达式:i=$(( (i + 1) % 5 ))。序列:{1..10}。截断字符串:${var%suffix}和${var#prefix}。例如,假设var=foo.pdf,那么echo ${var%.pdf}.txt将输出foo.txt。 -
Brace expansion using
{…}can reduce having to re-type similar text and automate combinations of items. This is helpful in examples likemv foo.{txt,pdf} some-dir(which moves both files),cp somefile{,.bak}(which expands tocp somefile somefile.bak) ormkdir -p test-{a,b,c}/subtest-{1,2,3}(which expands all possible combinations and creates a directory tree). Brace expansion is performed before any other expansion.使用括号扩展(
{…})来减少输入相似文本,并自动化文本组合。这在某些情况下会很有用,例如mv foo.{txt,pdf} some-dir(同时移动两个文件),cp somefile{,.bak}(会被扩展成cp somefile somefile.bak)或者mkdir -p test-{a,b,c}/subtest-{1,2,3}(会被扩展成所有可能的组合,并创建一个目录树)。 -
The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion. (For example, a range like
{1..20}cannot be expressed with variables using{$a..$b}. Useseqor aforloop instead, e.g.,seq $a $borfor((i=a; i<=b; i++)); do ... ; done.)Bash 的展开顺序是:花括号展开;从左到右进行波浪号展开、参数和变量展开、算术展开以及命令替换;接着分词,最后进行文件名展开。例如,不能把
{1..20}写成{$a..$b}来指定变量范围。可以改用seq $a $b或for((i=a; i<=b; i++)); do ... ; done。 -
The output of a command can be treated like a file via
<(some command)(known as process substitution). For example, compare local/etc/hostswith a remote one:通过使用
<(some command)可以将输出视为文件。例如,对比本地文件/etc/hosts和一个远程文件:
diff /etc/hosts <(ssh somehost cat /etc/hosts)
-
When writing scripts you may want to put all of your code in curly braces. If the closing brace is missing, your script will be prevented from executing due to a syntax error. This makes sense when your script is going to be downloaded from the web, since it prevents partially downloaded scripts from executing:
编写脚本时,你可能会想要把代码都放在大括号里。缺少右括号的话,代码就会因为语法错误而无法执行。如果你的脚本是要放在网上分享供他人使用的,这样的写法就体现出它的好处了,因为这样可以防止下载不完全代码被执行。
{
# Your code here
}
{
# 在这里写代码
}
-
A “here document” allows redirection of multiple lines of input as if from a file:
了解 Bash 中的“here documents”,例如
cat <<EOF ...。
cat <<EOF
input
on multiple lines
EOF
-
In Bash, redirect both standard output and standard error via:
some-command >logfile 2>&1orsome-command &>logfile. Often, to ensure a command does not leave an open file handle to standard input, tying it to the terminal you are in, it is also good practice to add</dev/null.在 Bash 中,同时重定向标准输出和标准错误:
some-command >logfile 2>&1或者some-command &>logfile。通常,为了保证命令不会在标准输入里残留一个未关闭的文件句柄捆绑在你当前所在的终端上,在命令后添加</dev/null是一个好习惯。 -
Use
man asciifor a good ASCII table, with hex and decimal values. For general encoding info,man unicode,man utf-8, andman latin1are helpful.使用
man ascii查看具有十六进制和十进制值的ASCII表。man unicode,man utf-8,以及man latin1有助于你去了解通用的编码信息。 -
In ssh, knowing how to port tunnel with
-Lor-D(and occasionally-R) is useful, e.g. to access web sites from a remote server.ssh 中,了解如何使用
-L或-D(偶尔需要用-R)开启隧道是非常有用的,比如当你需要从一台远程服务器上访问 web 页面。 -
It can be useful to make a few optimizations to your ssh configuration; for example, this
~/.ssh/configcontains settings to avoid dropped connections in certain network environments, uses compression (which is helpful with scp over low-bandwidth connections), and multiplex channels to the same server with a local control file:对 ssh 设置做一些小优化可能是很有用的,例如这个
~/.ssh/config文件包含了防止特定网络环境下连接断开、压缩数据、多通道等选项:
TCPKeepAlive=yes
ServerAliveInterval=15
ServerAliveCountMax=6
Compression=yes
ControlMaster auto
ControlPath /tmp/%r@%h:%p
ControlPersist yes
-
A few other options relevant to ssh are security sensitive and should be enabled with care, e.g. per subnet or host or in trusted networks:
StrictHostKeyChecking=no,ForwardAgent=yes一些其他的关于 ssh 的选项是与安全相关的,应当小心翼翼的使用。例如你应当只能在可信任的网络中启用
StrictHostKeyChecking=no,ForwardAgent=yes。 -
To get the permissions on a file in octal form, which is useful for system configuration but not available in
lsand easy to bungle, use something like获取八进制形式的文件访问权限(修改系统设置时通常需要,但
ls的功能不那么好用并且通常会搞砸),可以使用类似如下的代码:
stat -c '%A %a %n' /etc/timezone
-
For interaction with files based on the output of another command (like
git), usefpp(PathPicker).使用
fpp(PathPicker)可以与基于另一个命令(例如git)输出的文件交互。 -
For a simple web server for all files in the current directory (and subdirs), available to anyone on your network, use:
python -m SimpleHTTPServer 7777(for port 7777 and Python 2) andpython -m http.server 7777(for port 7777 and Python 3).将 web 服务器上当前目录下所有的文件(以及子目录)暴露给你所处网络的所有用户,使用:
python -m SimpleHTTPServer 7777(使用端口 7777 和 Python 2)或python -m http.server 7777(使用端口 7777 和 Python 3)。 -
For running a command as another user, use
sudo. Defaults to running as root; use-uto specify another user. Use-ito login as that user (you will be asked for your password).以其他用户的身份执行命令,使用
sudo。默认以 root 用户的身份执行;使用-u来指定其他用户。使用-i来以该用户登录(需要输入_你自己的_密码)。 -
For switching the shell to another user, use
su usernameorsu - username. The latter with ”-” gets an environment as if another user just logged in. Omitting the username defaults to root. You will be asked for the password of the user you are switching to.将 shell 切换为其他用户,使用
su username或者su - username。加入-会使得切换后的环境与使用该用户登录后的环境相同。省略用户名则默认为 root。切换到哪个用户,就需要输入_哪个用户的_密码。 -
Know about the 128K limit on command lines. This “Argument list too long” error is common when wildcard matching large numbers of files. (When this happens alternatives like
findandxargsmay help.)了解命令行的 128K 限制。使用通配符匹配大量文件名时,常会遇到“Argument list too long”的错误信息。(这种情况下换用
find或xargs通常可以解决。) -
For a basic calculator (and of course access to Python in general), use the
pythoninterpreter. For example,当你需要一个基本的计算器时,可以使用
python解释器(当然你要用 python 的时候也是这样)。例如:
>>> 2+3
5
Processing files and data文件及数据处理
-
To locate a file by name in the current directory,
find . -iname '*something*'(or similar). To find a file anywhere by name, uselocate something(but bear in mindupdatedbmay not have indexed recently created files).在当前目录下通过文件名查找一个文件,使用类似于这样的命令:
find . -iname '*something*'。在所有路径下通过文件名查找文件,使用locate something(但注意到updatedb可能没有对最近新建的文件建立索引,所以你可能无法定位到这些未被索引的文件)。 -
To convert HTML to text:
lynx -dump -stdin将 HTML 转为文本:
lynx -dump -stdin。 -
If you must handle XML,
xmlstarletis old but good.当你要处理棘手的 XML 时候,
xmlstarlet算是上古时代流传下来的神器。 -
Know about
sortanduniq, including uniq’s-uand-doptions — see one-liners below. See alsocomm.了解如何使用
sort和uniq,包括 uniq 的-u参数和-d参数,具体内容在后文单行脚本节中。另外可以了解一下comm。 -
Know about
cut,paste, andjointo manipulate text files. Many people usecutbut forget aboutjoin.了解如何使用
cut,paste和join来更改文件。很多人都会使用cut,但遗忘了join。 -
Know about
wcto count newlines (-l), characters (-m), words (-w) and bytes (-c).了解如何运用
wc去计算新行数(-l),字符数(-m),单词数(-w)以及字节数(-c)。 -
Know about
teeto copy from stdin to a file and also to stdout, as inls -al | tee file.txt.了解如何使用
tee将标准输入复制到文件甚至标准输出,例如ls -al | tee file.txt。 -
Know that locale affects a lot of command line tools in subtle ways, including sorting order (collation) and performance. Most Linux installations will set
LANGor other locale variables to a local setting like US English. But be aware sorting will change if you change locale. And know i18n routines can make sort or other commands run many times slower. In some situations (such as the set operations or uniqueness operations below) you can safely ignore slow i18n routines entirely and use traditional byte-based sort order, usingexport LC_ALL=C.注意到语言设置(中文或英文等)对许多命令行工具有一些微妙的影响,比如排序的顺序和性能。大多数 Linux 的安装过程会将
LANG或其他有关的变量设置为符合本地的设置。要意识到当你改变语言设置时,排序的结果可能会改变。明白国际化可能会使 sort 或其他命令运行效率下降许多倍。某些情况下(例如集合运算)你可以放心的使用export LC_ALL=C来忽略掉国际化并按照字节来判断顺序。 -
You can set a specific command’s environment by prefixing its invocation with the environment variable settings, as in
TZ=Pacific/Fiji date.你可以单独指定某一条命令的环境,只需在调用时把环境变量设定放在命令的前面,例如
TZ=Pacific/Fiji date可以获取斐济的时间。 -
Know basic
awkandsedfor simple data munging. See One-liners for examples.了解如何使用
awk和sed来进行简单的数据处理。 参阅 One-liners 获取示例。 -
To replace all occurrences of a string in place, in one or more files:
替换一个或多个文件中出现的字符串:
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
-
To rename multiple files and/or search and replace within files, try
repren. (In some cases therenamecommand also allows multiple renames, but be careful as its functionality is not the same on all Linux distributions.)使用
repren来批量重命名文件,或是在多个文件中搜索替换内容。(有些时候rename命令也可以批量重命名,但要注意,它在不同 Linux 发行版中的功能并不完全一样。)
# Full rename of filenames, directories, and contents foo -> bar:
repren --full --preserve-case --from foo --to bar .
# Recover backup files whatever.bak -> whatever:
repren --renames --from '(.*)\.bak' --to '\1' *.bak
# Same as above, using rename, if available:
rename 's/\.bak$//' *.bak
# 将文件、目录和内容全部重命名 foo -> bar:
repren --full --preserve-case --from foo --to bar .
# 还原所有备份文件 whatever.bak -> whatever:
repren --renames --from '(.*)\.bak' --to '\1' *.bak
# 用 rename 实现上述功能(若可用):
rename 's/\.bak$//' *.bak
-
As the man page says,
rsyncreally is a fast and extraordinarily versatile file copying tool. It’s known for synchronizing between machines but is equally useful locally. When security restrictions allow, usingrsyncinstead ofscpallows recovery of a transfer without restarting from scratch. It also is among the fastest ways to delete large numbers of files:根据 man 页面的描述,
rsync是一个快速且非常灵活的文件复制工具。它闻名于设备之间的文件同步,但其实它在本地情况下也同样有用。在安全设置允许下,用rsync代替scp可以实现文件续传,而不用重新从头开始。它同时也是删除大量文件的最快方法之一:
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
-
Use
shufto shuffle or select random lines from a file.使用
shuf可以以行为单位来打乱文件的内容或从一个文件中随机选取多行。 -
Know
sort’s options. For numbers, use-n, or-hfor handling human-readable numbers (e.g. fromdu -h). Know how keys work (-tand-k). In particular, watch out that you need to write-k1,1to sort by only the first field;-k1means sort according to the whole line. Stable sort (sort -s) can be useful. For example, to sort first by field 2, then secondarily by field 1, you can usesort -k1,1 | sort -s -k2,2.了解
sort的参数。显示数字时,使用-n或者-h来显示更易读的数(例如du -h的输出)。明白排序时关键字的工作原理(-t和-k)。例如,注意到你需要-k1,1来仅按第一个域来排序,而-k1意味着按整行排序。稳定排序(sort -s)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用sort -k1,1 | sort -s -k2,2。 -
If you ever need to write a tab literal in a command line in Bash (e.g. for the -t argument to sort), press ctrl-v [Tab] or write
$'\t'(the latter is better as you can copy/paste it).如果你想在 Bash 命令行中写 tab 制表符,按下 ctrl-v [Tab] 或键入
$'\t'(后者可能更好,因为你可以复制粘贴它)。 -
The standard tools for patching source code are
diffandpatch. See alsodiffstatfor summary statistics of a diff andsdifffor a side-by-side diff. Notediff -rworks for entire directories. Usediff -r tree1 tree2 | diffstatfor a summary of changes. Usevimdiffto compare and edit files.标准的源代码对比及合并工具是
diff和patch。使用diffstat查看变更总览数据。注意到diff -r对整个文件夹有效。使用diff -r tree1 tree2 | diffstat查看变更的统计数据。vimdiff用于比对并编辑文件。 -
For binary files, use
hd,hexdumporxxdfor simple hex dumps andbvi,hexeditorbiewfor binary editing.对于二进制文件,使用
hd,hexdump或者xxd使其以十六进制显示,使用bvi,hexedit或者biew来进行二进制编辑。 -
Also for binary files,
strings(plusgrep, etc.) lets you find bits of text.同样对于二进制文件,
strings(包括grep等工具)可以帮助在二进制文件中查找特定比特。 -
For binary diffs (delta compression), use
xdelta3.制作二进制差分文件(Delta 压缩),使用
xdelta3。 -
To convert text encodings, try
iconv. Oruconvfor more advanced use; it supports some advanced Unicode things. For example:使用
iconv更改文本编码。需要更高级的功能,可以使用uconv,它支持一些高级的 Unicode 功能。例如,这条命令移除了所有重音符号:
# Displays hex codes or actual names of characters (useful for debugging):
uconv -f utf-8 -t utf-8 -x '::Any-Hex;' < input.txt
uconv -f utf-8 -t utf-8 -x '::Any-Name;' < input.txt
# Lowercase and removes all accents (by expanding and dropping them):
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC;' < input.txt > output.txt
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC; ' < input.txt > output.txt
-
To split files into pieces, see
split(to split by size) andcsplit(to split by a pattern).拆分文件可以使用
split(按大小拆分)和csplit(按模式拆分)。 -
Date and time: To get the current date and time in the helpful ISO 8601 format, use
date -u +"%Y-%m-%dT%H:%M:%SZ"(other options are problematic). To manipulate date and time expressions, usedateadd,datediff,strptimeetc. fromdateutils.操作日期和时间表达式,可以用
dateutils中的dateadd、datediff、strptime等工具。 -
Use
zless,zmore,zcat, andzgrepto operate on compressed files.使用
zless、zmore、zcat和zgrep对压缩过的文件进行操作。 -
File attributes are settable via
chattrand offer a lower-level alternative to file permissions. For example, to protect against accidental file deletion the immutable flag:sudo chattr +i /critical/directory/or/file文件属性可以通过
chattr进行设置,它比文件权限更加底层。例如,为了保护文件不被意外删除,可以使用不可修改标记:sudo chattr +i /critical/directory/or/file -
Use
getfaclandsetfaclto save and restore file permissions. For example:使用
getfacl和setfacl以保存和恢复文件权限。例如:
getfacl -R /some/path > permissions.txt
setfacl --restore=permissions.txt
-
To create empty files quickly, use
truncate(creates sparse file),fallocate(ext4, xfs, btrfs and ocfs2 filesystems),xfs_mkfile(almost any filesystems, comes in xfsprogs package),mkfile(for Unix-like systems like Solaris, Mac OS).为了高效地创建空文件,请使用
truncate(创建稀疏文件),fallocate(用于 ext4,xfs,btrf 和 ocfs2 文件系统),xfs_mkfile(适用于几乎所有的文件系统,包含在 xfsprogs 包中),mkfile(用于类 Unix 操作系统,比如 Solaris 和 Mac OS)。
System debugging系统调试
-
To know current cpu/disk status, the classic tools are
top(or the betterhtop),iostat, andiotop. Useiostat -mxz 15for basic CPU and detailed per-partition disk stats and performance insight.获取 CPU 和硬盘的使用状态,通常使用使用
top(htop更佳),iostat和iotop。而iostat -mxz 15可以让你获悉 CPU 和每个硬盘分区的基本信息和性能表现。 -
For network connection details, use
netstatandss.使用
netstat和ss查看网络连接的细节。 -
To know memory status, run and understand the output of
freeandvmstat. In particular, be aware the “cached” value is memory held by the Linux kernel as file cache, so effectively counts toward the “free” value.若要了解内存状态,运行并理解
free和vmstat的输出。值得留意的是“cached”的值,它指的是 Linux 内核用来作为文件缓存的内存大小,而与空闲内存无关。 -
Java system debugging is a different kettle of fish, but a simple trick on Oracle’s and some other JVMs is that you can run
kill -3 <pid>and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. The JDK’sjps,jstat,jstack,jmapare useful. SJK tools are more advanced.Java 系统调试则是一件截然不同的事,一个可以用于 Oracle 的 JVM 或其他 JVM 上的调试的技巧是你可以运行
kill -3 <pid>同时一个完整的栈轨迹和堆概述(包括 GC 的细节)会被保存到标准错误或是日志文件。JDK 中的jps,jstat,jstack,jmap很有用。SJK tools 更高级。 -
The
abtool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, trysiege.ab工具(Apache 中自带)可以简单粗暴地检查 web 服务器的性能。对于更复杂的负载测试,使用siege。 -
Know about
straceandltrace. These can be helpful if a program is failing, hanging, or crashing, and you don’t know why, or if you want to get a general idea of performance. Note the profiling option (-c), and the ability to attach to a running process (-p). Use trace child option (-f) to avoid missing important calls.了解
strace和ltrace。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意 profile 参数(-c)和附加到一个运行的进程参数 (-p)。 -
Know about
lddto check shared libraries etc — but never run it on untrusted files.了解使用
ldd来检查共享库。但是永远不要在不信任的文件上运行。 -
Know how to connect to a running process with
gdband get its stack traces.了解如何运用
gdb连接到一个运行着的进程并获取它的堆栈轨迹。 -
Use
/proc. It’s amazingly helpful sometimes when debugging live problems. Examples:/proc/cpuinfo,/proc/meminfo,/proc/cmdline,/proc/xxx/cwd,/proc/xxx/exe,/proc/xxx/fd/,/proc/xxx/smaps(wherexxxis the process id or pid).学会使用
/proc。它在调试正在出现的问题的时候有时会效果惊人。比如:/proc/cpuinfo,/proc/meminfo,/proc/cmdline,/proc/xxx/cwd,/proc/xxx/exe,/proc/xxx/fd/,/proc/xxx/smaps(这里的xxx表示进程的 id 或 pid)。 -
Check what OS you’re on with
unameoruname -a(general Unix/kernel info) orlsb_release -a(Linux distro info).查看你当前使用的系统,使用
uname,uname -a(Unix/kernel 信息)或者lsb_release -a(Linux 发行版信息)。 -
Use
dmesgwhenever something’s acting really funny (it could be hardware or driver issues).无论什么东西工作得很欢乐(可能是硬件或驱动问题)时可以试试
dmesg。 -
If you delete a file and it doesn’t free up expected disk space as reported by
du, check whether the file is in use by a process:lsof | grep deleted | grep "filename-of-my-big-file"如果你删除了一个文件,但通过
du发现没有释放预期的磁盘空间,请检查文件是否被进程占用:lsof | grep deleted | grep "filename-of-my-big-file"
One-liners单行脚本
A few examples of piecing together commands:
一些命令组合的例子:
-
It is remarkably helpful sometimes that you can do set intersection, union, and difference of text files via
sort/uniq. Supposeaandbare text files that are already uniqued. This is fast, and works on files of arbitrary size, up to many gigabytes. (Sort is not limited by memory, though you may need to use the-Toption if/tmpis on a small root partition.) See also the note aboutLC_ALLabove andsort’s-uoption (left out for clarity below).当你需要对文本文件做集合交、并、差运算时,
sort和uniq会是你的好帮手。具体例子请参照代码后面的,此处假设a与b是两内容不同的文件。这种方式效率很高,并且在小文件和上 G 的文件上都能运用(注意尽管在/tmp在一个小的根分区上时你可能需要-T参数,但是实际上sort并不被内存大小约束),参阅前文中关于LC_ALL和sort的-u参数的部分。
sort a b | uniq > c # c is a union b
sort a b | uniq -d > c # c is a intersect b
sort a b b | uniq -u > c # c is set difference a - b
sort a b | uniq > c # c 是 a 并 b
sort a b | uniq -d > c # c 是 a 交 b
sort a b b | uniq -u > c # c 是 a - b
-
Pretty-print two JSON files, normalizing their syntax, then coloring and paginating the result:
比较两个 JSON 文件时,可以先统一语法和键的顺序,再给差异着色并分页阅读。
diff <(jq --sort-keys . < file1.json) <(jq --sort-keys . < file2.json) | colordiff | less -R
-
Use
grep . *to quickly examine the contents of all files in a directory (so each line is paired with the filename), orhead -100 *(so each file has a heading). This can be useful for directories filled with config settings like those in/sys,/proc,/etc.使用
grep . *(每行都会附上文件名)或者head -100 *(每个文件有一个标题)来阅读检查目录下所有文件的内容。这在检查一个充满配置文件的目录(如/sys、/proc、/etc)时特别好用。 -
Summing all numbers in the third column of a text file (this is probably 3X faster and 3X less code than equivalent Python):
计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码快三倍且代码量少三倍):
awk '{ x += $3 } END { print x }' myfile
-
To see sizes/dates on a tree of files, this is like a recursive
ls -lbut is easier to read thanls -lR:如果你想在文件树上查看大小/日期,这可能看起来像递归版的
ls -l但比ls -lR更易于理解:
find . -type f -ls
-
Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an
acct_idparameter that is present in the URL. If you want a tally of how many requests for eachacct_id:假设你有一个类似于 web 服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个
acct_id参数在 URI 中。如果你想计算出每个acct_id值有多少次请求,使用如下代码:
egrep -o 'acct_id=[0-9]+' access.log | cut -d= -f2 | sort | uniq -c | sort -rn
-
To continuously monitor changes, use
watch, e.g. check changes to files in a directory withwatch -d -n 2 'ls -rtlh | tail'or to network settings while troubleshooting your wifi settings withwatch -d -n 2 ifconfig.要持续监测文件改动,可以使用
watch,例如检查某个文件夹中文件的改变,可以用watch -d -n 2 'ls -rtlh | tail';或者在排查 WiFi 设置故障时要监测网络设置的更改,可以用watch -d -n 2 ifconfig。 -
Run this function to get a random tip from this document (parses Markdown and extracts an item):
运行这个函数从这篇文档中随机获取一条技巧(解析 Markdown 文件并抽取项目):
function taocl() {
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
sed '/cowsay[.]png/d' |
pandoc -f markdown -t html |
xmlstarlet fo --html --dropdtd |
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
xmlstarlet unesc | fmt -80 | iconv -t US
}
function taocl() {
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README-zh.md|
pandoc -f markdown -t html |
iconv -f 'utf-8' -t 'unicode' |
xmlstarlet fo --html --dropdtd |
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
xmlstarlet unesc | fmt -80
}
Obscure but useful冷门但有用
-
expr: perform arithmetic or boolean operations or evaluate regular expressionsexpr:计算表达式或正则匹配 -
m4: simple macro processorm4:简单的宏处理器 -
yes: print a string a lotyes:多次打印字符串 -
cal: nice calendarcal:漂亮的日历 -
env: run a command (useful in scripts)env:执行一个命令(脚本文件中很有用) -
printenv: print out environment variables (useful in debugging and scripts)printenv:打印环境变量(调试时或在写脚本文件时很有用) -
look: find English words (or lines in a file) beginning with a stringlook:查找以特定字符串开头的单词或行 -
cut,pasteandjoin: data manipulationcut,paste和join:数据修改 -
fmt: format text paragraphsfmt:格式化文本段落 -
pr: format text into pages/columnspr:将文本格式化成页/列形式 -
fold: wrap lines of textfold:包裹文本中的几行 -
column: format text fields into aligned, fixed-width columns or tablescolumn:将文本格式化成多个对齐、定宽的列或表格 -
expandandunexpand: convert between tabs and spacesexpand和unexpand:制表符与空格之间转换 -
nl: add line numbersnl:添加行号 -
seq: print numbersseq:打印数字 -
bc: calculatorbc:计算器 -
factor: factor integersfactor:分解因数 -
toe: table of terminfo entriestoe:terminfo 入口列表 -
nc: network debugging and data transfernc:网络调试及数据传输 -
socat: socket relay and tcp port forwarder (similar tonetcat)socat:套接字代理,与netcat类似 -
dd: moving data between files or devicesdd:文件或设备间传输数据 -
file: identify type of a filefile:确定文件类型 -
tree: display directories and subdirectories as a nesting tree; likelsbut recursivetree:以树的形式显示路径和文件,类似于递归的ls -
stat: file infostat:文件信息 -
time: execute and time a commandtime:执行命令,并计算执行时间 -
timeout: execute a command for specified amount of time and stop the process when the specified amount of time completes.timeout:在指定时长范围内执行命令,并在规定时间结束后停止进程 -
lockfile: create semaphore file that can only be removed byrm -flockfile:使文件只能通过rm -f移除 -
logrotate: rotate, compress and mail logs.logrotate: 切换、压缩以及发送日志文件 -
watch: run a command repeatedly, showing results and/or highlighting changeswatch:重复运行同一个命令,展示结果并/或高亮有更改的部分 -
when-changed: runs any command you specify whenever it sees file changed. Seeinotifywaitandentras well.when-changed:当检测到文件更改时执行指定命令。参阅inotifywait和entr。 -
tac: print files in reversetac:反向输出文件 -
shuf: select lines at random from a fileshuf:文件中随机选取几行 -
comm: compare sorted files line by linecomm:一行一行的比较排序过的文件 -
strings: extract text from binary filesstrings:从二进制文件中抽取文本 -
tr: character translation or manipulationtr:转换字母 -
iconvoruconv: conversion for text encodingsiconv或uconv:文本编码转换 -
splitandcsplit: splitting filessplit和csplit:分割文件 -
sponge: read all input before writing it, useful for reading from then writing to the same file, e.g.,grep -v something some-file | sponge some-filesponge:在写入前读取所有输入,在读取文件后再向同一文件写入时比较有用,例如grep -v something some-file | sponge some-file -
units: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also/usr/share/units/definitions.units)units:将一种计量单位转换为另一种等效的计量单位(参阅/usr/share/units/definitions.units) -
apg: generates random passwordsapg:随机生成密码 -
xz: high-ratio file compressionxz:高比例的文件压缩 -
ldd: dynamic library infoldd:动态库信息 -
nm: symbols from object filesnm:提取 obj 文件中的符号 -
strace: system call debuggingstrace:调试系统调用 -
cssh: visual concurrent shellcssh:可视化的并发 shell -
rsync: sync files and folders over SSH or in local file systemrsync:通过 ssh 或本地文件系统同步文件和文件夹 -
hostanddig: DNS lookupshost和dig:DNS 查找 -
lsof: process file descriptor and socket infolsof:列出当前系统打开文件的工具以及查看端口信息 -
dstat: useful system statsdstat:系统状态查看 -
iostat: Disk usage statsiostat:硬盘使用状态 -
mpstat: CPU usage statsmpstat: CPU 使用状态 -
vmstat: Memory usage statsvmstat: 内存使用状态 -
htop: improved version of tophtop:top 的加强版 -
last: login historylast:登入记录 -
w: who’s logged onw:查看处于登录状态的用户 -
id: user/group identity infoid:用户/组 ID 信息 -
ss: socket statisticsss:套接字数据 -
dmesg: boot and system error messagesdmesg:引导及系统错误信息 -
sysctl: view and configure Linux kernel parameters at run timesysctl: 在内核运行时动态地查看和修改内核的运行参数 -
hdparm: SATA/ATA disk manipulation/performancehdparm:SATA/ATA 磁盘更改及性能分析 -
lsblk: list block devices: a tree view of your disks and disk partitionslsblk:列出块设备信息:以树形展示你的磁盘以及磁盘分区信息 -
lshw,lscpu,lspci,lsusb,dmidecode: hardware information, including CPU, BIOS, RAID, graphics, devices, etc.lshw,lscpu,lspci,lsusb和dmidecode:查看硬件信息,包括 CPU、BIOS、RAID、显卡、USB设备等 -
lsmodandmodinfo: List and show details of kernel modules.lsmod和modinfo:列出内核模块,并显示其细节 -
fortune,ddate, andsl: um, well, it depends on whether you consider steam locomotives and Zippy quotations “useful”fortune,ddate和sl:额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否“有用”
macOS only仅限 OS X 系统
These are items relevant only on macOS.
以下是仅限于 OS X 系统的技巧。
-
Package management with
brew(Homebrew) and/orport(MacPorts). These can be used to install on macOS many of the above commands.用
brew(Homebrew)或者port(MacPorts)进行包管理。这些可以用来在 OS X 系统上安装以上的大多数命令。 -
Copy output of any command to a desktop app with
pbcopyand paste input from one withpbpaste.用
pbcopy复制任何命令的输出到桌面应用,用pbpaste粘贴输入。 -
To enable the Option key in macOS Terminal as an alt key (such as used in the commands above like alt-b, alt-f, etc.), open Preferences -> Profiles -> Keyboard and select “Use Option as Meta key”.
若要在 OS X 终端中将 Option 键视为 alt 键(例如在上面介绍的 alt-b、alt-f 等命令中用到),打开 偏好设置 -> 描述文件 -> 键盘 并勾选“使用 Option 键作为 Meta 键”。
-
To open a file with a desktop app, use
openoropen -a /Applications/Whatever.app.用
open或者open -a /Applications/Whatever.app使用桌面应用打开文件。 -
Spotlight: Search files with
mdfindand list metadata (such as photo EXIF info) withmdls.Spotlight:用
mdfind搜索文件,用mdls列出元数据(例如照片的 EXIF 信息)。 -
Be aware macOS is based on BSD Unix, and many commands (for example
ps,ls,tail,awk,sed) have many subtle variations from Linux, which is largely influenced by System V-style Unix and GNU tools. You can often tell the difference by noting a man page has the heading “BSD General Commands Manual.” In some cases GNU versions can be installed, too (such asgawkandgsedfor GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python orperl) or test carefully.注意 OS X 系统是基于 BSD UNIX 的,许多命令(例如
ps,ls,tail,awk,sed)都和 Linux 中有微妙的不同( Linux 很大程度上受到了 System V-style Unix 和 GNU 工具影响)。你可以通过标题为 “BSD General Commands Manual” 的 man 页面发现这些不同。在有些情况下 GNU 版本的命令也可能被安装(例如gawk和gsed对应 GNU 中的 awk 和 sed )。如果要写跨平台的 Bash 脚本,避免使用这些命令(例如,考虑 Python 或者perl)或者经过仔细的测试。 -
To get macOS release information, use
sw_vers.用
sw_vers获取 OS X 的版本信息。
Windows only仅限 Windows 系统
These items are relevant only on Windows.
以下是仅限于 Windows 系统的技巧。
Ways to obtain Unix tools under Windows在 Windows 下获取 Unix 工具
-
On Windows 10, you can use Windows Subsystem for Linux (WSL), which provides a familiar Bash environment with Unix command line utilities.
在 Windows 10 上,你可以使用 Bash on Ubuntu on Windows,它提供了一个熟悉的 Bash 环境,包含了不少 Unix 命令行工具。好处是它允许 Linux 上编写的程序在 Windows 上运行,而另一方面,Windows 上编写的程序却无法在 Bash 命令行中运行。
-
If you mainly want to use GNU developer tools (such as GCC) on Windows, consider MinGW and its MSYS package, which provides utilities such as bash, gawk, make and grep. MSYS doesn’t have all the features compared to Cygwin. MinGW is particularly useful for creating native Windows ports of Unix tools.
Useful Windows command-line tools实用 Windows 命令行工具
-
You can perform and script most Windows system administration tasks from the command line by learning and using
wmic.可以使用
wmic在命令行环境下给大部分 Windows 系统管理任务编写脚本以及执行这些任务。 -
Native command-line Windows networking tools you may find useful include
ping,ipconfig,tracert, andnetstat.Windows 实用的原生命令行网络工具包括
ping,ipconfig,tracert,和netstat。 -
You can perform many useful Windows tasks by invoking the
Rundll32command.可以使用
Rundll32命令来实现许多有用的 Windows 任务 。
Cygwin tips and tricksCygwin 技巧
-
Install additional Unix programs with the Cygwin’s package manager.
通过 Cygwin 的包管理器来安装额外的 Unix 程序。
-
Use
minttyas your command-line window.使用
mintty作为你的命令行窗口。 -
Access the Windows clipboard through
/dev/clipboard.要访问 Windows 剪贴板,可以通过
/dev/clipboard。 -
Run
cygstartto open an arbitrary file through its registered application.运行
cygstart以通过默认程序打开一个文件。 -
Access the Windows registry with
regtool.要访问 Windows 注册表,可以使用
regtool。 -
Note that a
C:\Windows drive path becomes/cygdrive/cunder Cygwin, and that Cygwin’s/appears underC:\cygwinon Windows. Convert between Cygwin and Windows-style file paths withcygpath. This is most useful in scripts that invoke Windows programs.注意 Windows 驱动器路径
C:\在 Cygwin 中用/cygdrive/c代表,而 Cygwin 的/代表 Windows 中的C:\cygwin。要转换 Cygwin 和 Windows 风格的路径可以用cygpath。这在需要调用 Windows 程序的脚本里很有用。 -
You can perform and script most Windows system administration tasks from the command line by learning and using
wmic.学会使用
wmic,你就可以从命令行执行大多数 Windows 系统管理任务,并编成脚本。 -
If you mainly want to use GNU developer tools (such as GCC) on Windows, consider MinGW and its MSYS package, which provides utilities such as bash, gawk, make and grep. MSYS doesn’t have all the features compared to Cygwin. MinGW is particularly useful for creating native Windows ports of Unix tools.
More resources更多资源
-
awesome-shell: A curated list of shell tools and resources.
awesome-shell:一份精心组织的命令行工具及资源的列表。
-
awesome-osx-command-line: A more in-depth guide for the macOS command line.
awesome-osx-command-line:一份针对 OS X 命令行的更深入的指南。
-
Strict mode for writing better shell scripts.
Strict mode:为了编写更好的脚本文件。
-
shellcheck: A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
shellcheck:一个静态 shell 脚本分析工具,本质上是 bash/sh/zsh 的 lint。
-
Filenames and Pathnames in Shell: The sadly complex minutiae on how to handle filenames correctly in shell scripts.
Filenames and Pathnames in Shell:有关如何在 shell 脚本里正确处理文件名的细枝末节。
-
Data Science at the Command Line: More commands and tools helpful for doing data science, from the book of the same name
Data Science at the Command Line:用于数据科学的一些命令和工具,摘自同名书籍。
Disclaimer免责声明
With the exception of very small tasks, code is written so others can read it. With power comes responsibility. The fact you can do something in Bash doesn’t necessarily mean you should! ;)
除去特别小的工作,你编写的代码应当方便他人阅读。能力往往伴随着责任,你 有能力 在 Bash 中玩一些奇技淫巧并不意味着你应该去做!;)
License授权条款
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.