From 36b2ea3333b4aa8074f5d51928c19ce1cfdeee94 Mon Sep 17 00:00:00 2001 From: Chris Rhodes Date: Sun, 21 Jun 2015 23:54:34 +1000 Subject: [PATCH 01/69] Adding link to Tmux site Adding link to the tmux site --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 39bef86..08063d3 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ Notes: - Use `man ascii` for a good ASCII table, with hex and decimal values. For general encoding info, `man unicode`, `man utf-8`, and `man latin1` are helpful. -- Use `screen` or `tmux` to multiplex the screen, especially useful on remote ssh sessions and to detach and re-attach to a session. A more minimal alternative for session persistence only is `dtach`. +- Use `screen` or [`tmux`](https://tmux.github.io/) to multiplex the screen, especially useful on remote ssh sessions and to detach and re-attach to a session. A more minimal alternative for session persistence only is `dtach`. - In ssh, knowing how to port tunnel with `-L` or `-D` (and occasionally `-R`) is useful, e.g. to access web sites from a remote server. From e3e79e863c572cb35cde3efa974debb92e46bde9 Mon Sep 17 00:00:00 2001 From: Okunev Yu Dmitry Date: Mon, 22 Jun 2015 09:57:51 +0300 Subject: [PATCH 02/69] Added "pv" to "Obscure but useful" --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index dadbfd3..2904746 100644 --- a/README.md +++ b/README.md @@ -361,6 +361,8 @@ A few examples of piecing together commands: - `comm`: compare sorted files line by line +- `pv`: monitor the progress of data through a pipe + - `hd` and `bvi`: dump or edit binary files - `strings`: extract text from binary files From c327c3d9985d34b56f301c3e6d6866d627cfc43a Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Wed, 24 Jun 2015 15:34:17 +0800 Subject: [PATCH 03/69] README-zh.md: Use Full-width comma MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This change is made with GNU sed by using: gsed --in-place 's/,/,/g' README-zh.md gsed --in-place 's/, /,/g' README-zh.md --- README-zh.md | 164 +++++++++++++++++++++++++-------------------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/README-zh.md b/README-zh.md index c7977d2..b089527 100644 --- a/README-zh.md +++ b/README-zh.md @@ -14,70 +14,70 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -熟练使用命令行是一种常常被忽视或被认为晦涩难懂,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在Linux上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 +熟练使用命令行是一种常常被忽视或被认为晦涩难懂,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在Linux上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 这里的大部分内容 [首次](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [出现](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的issue/PR)。 +于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的issue/PR)。 ## 必读 涵盖范围: -- 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容), 具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为Linux所写,但很多内容(并非所有的)同样适用于MacOS甚至Cygwin。 -- 本文关注于交互式Bash,尽管很多技巧适用于其他shell或Bash脚本。 -- 本文包括了"标准的"Unix命令和需要安装特定包的命令,只要它们足够重要。 +- 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 +- 本文为Linux所写,但很多内容(并非所有的)同样适用于MacOS甚至Cygwin。 +- 本文关注于交互式Bash,尽管很多技巧适用于其他shell或Bash脚本。 +- 本文包括了"标准的"Unix命令和需要安装特定包的命令,只要它们足够重要。 注意事项: -- 为了能在一页内展示尽量多的东西, 一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令, 那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pip`/`brew` 来安装新程序。 +- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pip`/`brew` 来安装新程序。 - 使用 [Explainshell](http://explainshell.com/) 去获取相关命令、参数、管道等内容的解释。 ## 基础 -- 学习Bash的基础知识。具体来说, 输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的shell可能很好用,但Bash功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh, fish或其他的shell的话, 在你自己的电脑上会显得很方便, 但在很多情况下会限制你, 比如当你需要在服务器上工作时)。 +- 学习Bash的基础知识。具体来说,输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的shell可能很好用,但Bash功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh,fish或其他的shell的话,在你自己的电脑上会显得很方便,但在很多情况下会限制你,比如当你需要在服务器上工作时)。 - 学习并掌握至少一个基于文本的编辑器。通常 Vim (`vi`) 会是你最好的选择。 -- 学会如何使用`man`命令去阅读文档。学会使用`apropos`去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用`help`和`help -d`命令获取帮助信息。 +- 学会如何使用`man`命令去阅读文档。学会使用`apropos`去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用`help`和`help -d`命令获取帮助信息。 -- 学会使用`>`和`<`来重定向输出和输入,学会使用`|`来重定向管道。了解标准输出stdout和标准错误stderr。 +- 学会使用`>`和`<`来重定向输出和输入,学会使用`|`来重定向管道。了解标准输出stdout和标准错误stderr。 - 学会使用通配符`*` ( 若能`?`和`{`...`}`更好) 和引用以及引用中`'`和`"`的区别。 -- 熟悉Bash任务管理工具: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill` 等。 +- 熟悉Bash任务管理工具: `&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 -- 了解`ssh`, 以及基本的无密码认证, `ssh-agent`, `ssh-add`等。 +- 了解`ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add`等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义), `less`, `head`, `tail`和`tail -f` (甚至 `less +F`), `ln` and `ln -s` (了解软连接和硬连接的区别), `chown`, `chmod`, `du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`, `mount`, `fdisk`, `mkfs`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解软连接和硬连接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`。 -- 学习基本的网络管理: `ip` 或 `ifconfig`, `dig`。 +- 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 -- 熟悉正则表达式,以及`grep`/`egrep`里不同参数的作用,例如`-i`, `-o`, `-A`,和 `-B`。 +- 熟悉正则表达式,以及`grep`/`egrep`里不同参数的作用,例如`-i`,`-o`,`-A`,和 `-B`。 -- 学会使用`apt-get`, `yum`, 或`dnf` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令韩工具 (部分程序使用`pip`来安装会很简单)。 +- 学会使用`apt-get`,`yum`,或`dnf` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令韩工具 (部分程序使用`pip`来安装会很简单)。 ## 日常使用 -- 在Bash中,可以使用**Tab**自动补全参数,使用**ctrl-r**搜索命令行历史。 +- 在Bash中,可以使用**Tab**自动补全参数,使用**ctrl-r**搜索命令行历史。 -- 在Bash中,使用**ctrl-w**删除你键入的最后一个单词,使用**ctrl-u**删除整行,使用**alt-b**和**alt-f**按单词移动, 使用**ctrl-k**从光标处删除到行尾,使用**ctrl-l**清屏。键入`man readline`查看Bash中的默认快捷键,内容很多。例如**alt-.** 循环地移向前一个参数, 以及**alt-***展开通配符。 +- 在Bash中,使用**ctrl-w**删除你键入的最后一个单词,使用**ctrl-u**删除整行,使用**alt-b**和**alt-f**按单词移动,使用**ctrl-k**从光标处删除到行尾,使用**ctrl-l**清屏。键入`man readline`查看Bash中的默认快捷键,内容很多。例如**alt-.** 循环地移向前一个参数,以及**alt-***展开通配符。 -- 你喜欢的话,可以键入`set -o vi`来使用vi风格的快捷键。 +- 你喜欢的话,可以键入`set -o vi`来使用vi风格的快捷键。 -- 键入`history`查看命令行历史记录。其中有许多缩写, 例如`!$` (最后键入的参数)和`!!`(最后键入的命令),尽管通常被 **ctrl-r**和**alt-.**取代。 +- 键入`history`查看命令行历史记录。其中有许多缩写,例如`!$` (最后键入的参数)和`!!`(最后键入的命令),尽管通常被 **ctrl-r**和**alt-.**取代。 - 回到上一个工作路径: `cd -` -- 如果你输入命令的时候改变了注意,按下**alt-#**在行首添加`#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 +- 如果你输入命令的时候改变了注意,按下**alt-#**在行首添加`#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 -- 使用`xargs` ( 或`parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外, 使用`-I{}`会很方便。例如: +- 使用`xargs` ( 或`parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname @@ -87,41 +87,41 @@ - 使用`pgrep`和`pkill`根据名字查找进程或发送信号。 -- 了解你可以发往进程的信号的种类。比如,使用`kill -STOP [pid]`停止一个进程。使用`man 7 signal`查看详细列表。 +- 了解你可以发往进程的信号的种类。比如,使用`kill -STOP [pid]`停止一个进程。使用`man 7 signal`查看详细列表。 - 使用`nohup`或`disown`使一个后台进程持续运行。 - 使用`netstat -lntp`或`ss -plat`检查哪些进程在监听端口(默认是检查TCP端口; 使用参数`-u`检查UDP端口)。 -- 有关打开套接字和文件,请参阅`lsof`。 +- 有关打开套接字和文件,请参阅`lsof`。 -- 在Bash脚本中,使用`set -x`去调试输出,尽可能的使用严格模式,使用`set -e`令脚本在发生错误时退出而不是继续运行,使用`set -o pipefail`严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时, 使用`trap`。 +- 在Bash脚本中,使用`set -x`去调试输出,尽可能的使用严格模式,使用`set -e`令脚本在发生错误时退出而不是继续运行,使用`set -o pipefail`严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用`trap`。 -- 在Bash脚本中,子shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: +- 在Bash脚本中,子shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: ```bash # do something in current dir (cd /some/other/dir && other-command) # continue in original dir ``` -- 在Bash中, 注意到其中有许多形式的扩展。检查变量是否存在: `${name:?error message}`。例如, 当Bash脚本需要一个参数时, 可以使用这样的代码`input_file=${1:?usage: $0 input_file}`。数学表达式: `i=$(( (i + 1) % 5 ))`。序列: `{1..10}`。 截断字符串: `${var%suffix}`和`${var#prefix}`。例如,假设`var=foo.pdf`, 那么`echo ${var%.pdf}.txt`将输出`foo.txt`。 +- 在Bash中,注意到其中有许多形式的扩展。检查变量是否存在: `${name:?error message}`。例如,当Bash脚本需要一个参数时,可以使用这样的代码`input_file=${1:?usage: $0 input_file}`。数学表达式: `i=$(( (i + 1) % 5 ))`。序列: `{1..10}`。 截断字符串: `${var%suffix}`和`${var#prefix}`。例如,假设`var=foo.pdf`,那么`echo ${var%.pdf}.txt`将输出`foo.txt`。 -- 通过使用`<(some command)`可以将输出视为文件。例如, 对比本地文件`/etc/hosts`和一个远程文件: +- 通过使用`<(some command)`可以将输出视为文件。例如,对比本地文件`/etc/hosts`和一个远程文件: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- 了解Bash中的"here documents", 例如`cat <logfile 2>&1`。通常,为了保证命令不会在标准输入里残留一个打开了的文件句柄导致你当前所在的终端无法操作,添加`logfile 2>&1`。通常,为了保证命令不会在标准输入里残留一个打开了的文件句柄导致你当前所在的终端无法操作,添加` foo: rename 's/\.bak$//' *.bak - # Full rename of filenames, directories, and contents foo -> bar: + # Full rename of filenames,directories,and contents foo -> bar: repren --full --preserve-case --from foo --to bar . ``` - 使用`shuf`从一个文件中随机选取行。 -- 了解`sort`的参数。明白键的工作原理(`-t`和`-k`)。例如,注意到你需要`-k1,1`来仅按第一个域来排序,而`-k1`意味着按整行排序。 +- 了解`sort`的参数。明白键的工作原理(`-t`和`-k`)。例如,注意到你需要`-k1,1`来仅按第一个域来排序,而`-k1`意味着按整行排序。 -- 稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用`sort -k1,1 | sort -s -k2,2` +- 稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用`sort -k1,1 | sort -s -k2,2` -- 如果你想在Bash命令行中写tab制表符,按下**ctrl-v** **[Tab]** 或键入`$'\t'`(后者可能更好,因为你可以复制粘贴它)。 +- 如果你想在Bash命令行中写tab制表符,按下**ctrl-v** **[Tab]** 或键入`$'\t'`(后者可能更好,因为你可以复制粘贴它)。 - 标准的源代码对比及合并工具是`diff`和`patch`。使用`diffstat`查看变更总览数据。注意到`diff -r`对整个文件夹有效。使用`diff -r tree1 tree2 | diffstat`查看变更总览数据。 -- 对于二进制文件,使用`hd`使其以十六进制显示以及使用`bvi`来编辑二进制。 +- 对于二进制文件,使用`hd`使其以十六进制显示以及使用`bvi`来编辑二进制。 -- 同样对于二进制文件,使用`strings`(包括`grep`等等)允许你查找一些文本。 +- 同样对于二进制文件,使用`strings`(包括`grep`等等)允许你查找一些文本。 -- 二进制文件对比(Delta压缩),使用`xdelta3`。 +- 二进制文件对比(Delta压缩),使用`xdelta3`。 -- 使用`iconv`更改文本编码。而更高级的用法,可以使用`uconv`,它支持一些高级的Unicode功能。例如,这条命令将所有元音字母转为小写并移除了: +- 使用`iconv`更改文本编码。而更高级的用法,可以使用`uconv`,它支持一些高级的Unicode功能。例如,这条命令将所有元音字母转为小写并移除了: ```sh uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC; ' < input.txt > output.txt ``` -- 拆分文件,查看`split`(按大小拆分)和`csplit`(按模式拆分)。 +- 拆分文件,查看`split`(按大小拆分)和`csplit`(按模式拆分)。 -- 使用`zless`, `zmore`, `zcat`和`zgrep`对压缩过的文件进行操作。 +- 使用`zless`,`zmore`,`zcat`和`zgrep`对压缩过的文件进行操作。 ## 系统调试 -- `curl`和`curl -I`可以便捷地被应用于web调试中,它们的好兄弟`wget`也可以,或者是更潮流的[`httpie`](https://github.com/jakubroztocil/httpie)。 +- `curl`和`curl -I`可以便捷地被应用于web调试中,它们的好兄弟`wget`也可以,或者是更潮流的[`httpie`](https://github.com/jakubroztocil/httpie)。 - 使用`iostat`、`netstat`、`top` (`htop`更佳) 和`dstat`去获取硬盘、cpu和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 -- 若要对系统有一个深度的总体认识, 使用[`glances`](https://github.com/nicolargo/glances)。它在一个终端窗口中向你提供一些系统级的数据。这对于快速的检查各个子系统非常有帮助。 +- 若要对系统有一个深度的总体认识,使用[`glances`](https://github.com/nicolargo/glances)。它在一个终端窗口中向你提供一些系统级的数据。这对于快速的检查各个子系统非常有帮助。 -- 若要了解内存状态,运行并理解`free`和`vmstat`的输出。尤其注意"cached"的值,它指的是Linux内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 +- 若要了解内存状态,运行并理解`free`和`vmstat`的输出。尤其注意"cached"的值,它指的是Linux内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 -- Java系统调试则是一件截然不同的事,一个可以用于Oracle的JVM或其他JVM上的调试的小技巧是你可以运行`kill -3 `同时一个完整的栈轨迹和堆概述(包括GC的细节)会被保存到标准输出/日志文件。 +- Java系统调试则是一件截然不同的事,一个可以用于Oracle的JVM或其他JVM上的调试的小技巧是你可以运行`kill -3 `同时一个完整的栈轨迹和堆概述(包括GC的细节)会被保存到标准输出/日志文件。 -- 使用`mtr`去跟踪路由,用于确定网络问题。 +- 使用`mtr`去跟踪路由,用于确定网络问题。 -- 用`ncdu`来查看磁盘使用情况,它比常用的命令,如`du -sh *`,更节省时间。 +- 用`ncdu`来查看磁盘使用情况,它比常用的命令,如`du -sh *`,更节省时间。 -- 查找正在使用带宽的套接字连接或进程,使用`iftop`或`nethogs`。 +- 查找正在使用带宽的套接字连接或进程,使用`iftop`或`nethogs`。 -- `ab`工具(捆绑于Apache)可以简单粗暴地检查web服务器的性能。对于更复杂的负载测试,使用`siege`。 +- `ab`工具(捆绑于Apache)可以简单粗暴地检查web服务器的性能。对于更复杂的负载测试,使用`siege`。 -- `wireshark`,`tshark`和`ngrep`可用于复杂的网络调试。 +- `wireshark`,`tshark`和`ngrep`可用于复杂的网络调试。 -- 了解`strace`和`ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意profile参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 +- 了解`strace`和`ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意profile参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 - 了解使用`ldd`来检查共享库。 - 了解如何运用`gdb`连接到一个运行着的进程并获取它的堆栈轨迹。 -- 学会使用`/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`。 +- 学会使用`/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如: `/proc/cpuinfo`,`/proc/xxx/cwd`,`/proc/xxx/exe`,`/proc/xxx/fd/`,`/proc/xxx/smaps`。 -- 当调试一些之前出现的问题的时候,`sar`非常有用。它展示了cpu、内存以及网络等的历史数据。 +- 当调试一些之前出现的问题的时候,`sar`非常有用。它展示了cpu、内存以及网络等的历史数据。 -- 关于更深层次的系统分析以及性能分析,看看`stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), 以及[`sysdig`](https://github.com/draios/sysdig)。 +- 关于更深层次的系统分析以及性能分析,看看`stap` ([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 - 查看你当前使用的Linux发型版(大部分发行版有效): `lsb_release -a` @@ -259,32 +259,32 @@ 一些命令组合的例子: -- 当你需要对文本文件做集合交、并、差运算时,结合使用`sort`/`uniq`很有帮助。假设`a`与`b`是两内容不同的文件。这种方式效率很高, 并且在小文件和上G的文件上都能运用 (`sort`不被内存大小约束,尽管在`/tmp`在一个小的根分区上时你可能需要`-T`参数),参阅前文中关于`LC_ALL`和`sort`的`-u`参数的部分。 +- 当你需要对文本文件做集合交、并、差运算时,结合使用`sort`/`uniq`很有帮助。假设`a`与`b`是两内容不同的文件。这种方式效率很高,并且在小文件和上G的文件上都能运用 (`sort`不被内存大小约束,尽管在`/tmp`在一个小的根分区上时你可能需要`-T`参数),参阅前文中关于`LC_ALL`和`sort`的`-u`参数的部分。 ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- 使用`grep . *`来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如`/sys`、`/proc`、`/etc`。 +- 使用`grep . *`来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如`/sys`、`/proc`、`/etc`。 - 计算文本文件第三列中所有数的和(可能比同等作用的Python代码块三倍且代码量少三倍): ```sh awk '{ x += $3 } END { print x }' myfile ``` -- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的`ls -l`但比`ls -lR`更易于理解: +- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的`ls -l`但比`ls -lR`更易于理解: ```sh find . -type f -ls ``` -- 尽可能的使用`xargs`或`parallel`。。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外, 使用`-I{}`会很方便。例如: +- 尽可能的使用`xargs`或`parallel`。。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- 假设你有一个类似于web服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个`acct_id`参数在URI中。如果你想计算出每个`acct_id`值有多少次请求,使用如下代码: +- 假设你有一个类似于web服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个`acct_id`参数在URI中。如果你想计算出每个`acct_id`值有多少次请求,使用如下代码: ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` @@ -341,7 +341,7 @@ - `nc`: 网络调试及数据传输 -- `socat`: 套接字代理,与`netcat`类似 +- `socat`: 套接字代理,与`netcat`类似 - `slurm`: 网络可视化 @@ -349,7 +349,7 @@ - `file`: 确定文件类型 -- `tree`: 以树的形式显示路径和文件,类似于递归的`ls` +- `tree`: 以树的形式显示路径和文件,类似于递归的`ls` - `stat`: 文件信息 @@ -423,7 +423,7 @@ - `lshw`: 硬件信息 -- `fortune`,`ddate`和`sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" +- `fortune`,`ddate`和`sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" ## 更多资源 @@ -434,7 +434,7 @@ ## 免责声明 -除去特别微小的任务,记录下这些代码以便他人查看。责任往往伴随着能力,*可以*做并不意味着应该做。 +除去特别微小的任务,记录下这些代码以便他人查看。责任往往伴随着能力,*可以*做并不意味着应该做。 ## 授权条款 From c878d4e1683d0138468c96ffba3a818b9ef44efa Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Wed, 24 Jun 2015 17:09:45 +0800 Subject: [PATCH 04/69] REMOTE-zh.md: Fix typos --- README-zh.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README-zh.md b/README-zh.md index b089527..445c08a 100644 --- a/README-zh.md +++ b/README-zh.md @@ -60,7 +60,7 @@ - 熟悉正则表达式,以及`grep`/`egrep`里不同参数的作用,例如`-i`,`-o`,`-A`,和 `-B`。 -- 学会使用`apt-get`,`yum`,或`dnf` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令韩工具 (部分程序使用`pip`来安装会很简单)。 +- 学会使用`apt-get`,`yum`,或`dnf` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令行工具 (部分程序使用`pip`来安装会很简单)。 ## 日常使用 @@ -75,7 +75,7 @@ - 回到上一个工作路径: `cd -` -- 如果你输入命令的时候改变了注意,按下**alt-#**在行首添加`#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 +- 如果你输入命令的时候改变了主意,按下**alt-#**在行首添加`#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 - 使用`xargs` ( 或`parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: ```bash @@ -278,7 +278,7 @@ find . -type f -ls ``` -- 尽可能的使用`xargs`或`parallel`。。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: +- 尽可能的使用`xargs`或`parallel`。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname From 99a6214ab6fcc70852743363acec35aa7334b2ed Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Wed, 24 Jun 2015 08:08:39 -0700 Subject: [PATCH 05/69] Additional reference to comm. Fixes #105. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5131fc0..5174ab4 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ Notes: - For Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) is convenient and [`s4cmd`](https://github.com/bloomreach/s4cmd) is faster. Amazon's [`aws`](https://github.com/aws/aws-cli) is essential for other AWS-related tasks. -- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. +- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. See also `comm`. - Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`. From 1f461a98af44fb75396a10f9e97ad6b9941cffab Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Wed, 24 Jun 2015 08:14:10 -0700 Subject: [PATCH 06/69] Add lspci. Fixes #112. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5174ab4..0d890a1 100644 --- a/README.md +++ b/README.md @@ -429,7 +429,7 @@ A few examples of piecing together commands: - `lsblk`: List block devices: a tree view of your disks and disk paritions -- `lshw`: hardware information +- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. - `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" From aa20e47e0d03d48068fd22d99772315bccf11fbf Mon Sep 17 00:00:00 2001 From: kesu Date: Wed, 24 Jun 2015 15:28:50 +0000 Subject: [PATCH 07/69] Added bullet for alias. Fixes #119 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0d890a1..88187f6 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ Notes: - 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.) +- Use `alias` to create shortcuts or synonyms for commonly used commands. For example: `alias ll='ls -latr'` creates a new alias `ll`. + - Be familiar with Bash job management: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. - Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc. From c5f8712739df3063f9f3494ff3f7ab19d43c5557 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Wed, 24 Jun 2015 20:58:46 +0300 Subject: [PATCH 08/69] Initial translation. --- README-es.md | 450 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 450 insertions(+) create mode 100644 README-es.md diff --git a/README-es.md b/README-es.md new file mode 100644 index 0000000..6853d97 --- /dev/null +++ b/README-es.md @@ -0,0 +1,450 @@ +[ Languages: [中文](README-zh.md) [Español](README-es.md) ] + +# El Arte del Terminal + +- [Meta](#meta) +- [Fundamentos](#basics) +- [De uso diario](#everyday-use) +- [Procesamieto de archivos y datos](#processing-files-and-data) +- [Depuración del sistema](#system-debugging) +- [One-liners](#one-liners) +- [Obscuro pero útil](#obscure-but-useful) +- [Más recursos](#more-resources) +- [Advertencia](#disclaimer) + + +![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) + +Fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora s flexibilidad y productividad como ingeniero en ambas formas obvia y sutil. Esta es una selección de notas y consejos al uar el terminal que encontré útil cuando trabajó en Linux. Algunos consejos son elementales, y algunos bastante específico, sofisiticados, o oscuros. Esta página no es larga, pero si usa y and recuerda todos los puntos aquí, ustedes saben un montón. + +Gran parte esta +[originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +[appeared](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) +en [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +pero debido al interés mostrado ahí, parece que vale la pena usar Github, donde las personas con mayor talento que facílmente sugerir mejoras. Si yo vez un error o algo que podría ser mejor, por favor, cree un issue o PR! (Por supuesto revise la sección meta de PRs/issues primero.) + + +## Meta + +Alcance: + +- Esta guía es para ambos el principiante y el experimentado. 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. Many but not all items apply equally to MacOS (or even Cygwin). +- The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting. +- 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. + +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-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (as appropriate) to install new programs. +- Use [Explainshell](http://explainshell.com/) to get a helpful breakdown of what commands, options, pipes etc. do. + + +## Basics + +- Learn basic Bash. Actually, type `man bash` and 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). + +- Learn at least one text-based editor well. Ideally Vim (`vi`), as there's really no competition for random editing in a terminal (even if you use Emacs, a big IDE, or a modern hipster editor most of the time). + +- Know how to read documentation with `man` (for the inquisitive, `man man` lists the section numbers, e.g. 1 is "regular" commands, 5 is files/conventions, and 8 are for administration). Find man pages with `apropos`. Know that some commands are not executables, but Bash builtins, and that you can get help on them with `help` and `help -d`. + +- Learn about redirection of output and input using `>` and `<` and pipes using `|`. Learn about stdout and 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. + +- Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc. + +- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. + +- Basic network management: `ip` or `ifconfig`, `dig`. + +- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. + +- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). + + +## Everyday use + +- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. + +- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. + +- Alternatively, if you love vi-style key-bindings, use `set -o vi`. + +- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. + +- To go back to the previous working directory: `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. + +- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +```bash + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- `pstree -p` is a helpful display of the process tree. + +- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). + +- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` + +- Use `nohup` or `disown` if you want a background process to keep running forever. + +- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). + +- See also `lsof` for open sockets and files. + +- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. + +- 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 + # 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. + +- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +```sh + diff /etc/hosts <(ssh somehost cat /etc/hosts) +``` + +- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 ` foo: + rename 's/\.bak$//' *.bak + # Full rename of filenames, directories, and contents foo -> bar: + repren --full --preserve-case --from foo --to bar . +``` + +- Use `shuf` to shuffle or select random lines from a file. + +- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `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). + +- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. + +- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. + +- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. + +- For binary diffs (delta compression), use `xdelta3`. + +- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +```sh + 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) and `csplit` (to split by a pattern). + +- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. + + +## System debugging + +- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). + +- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. + +- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. + +- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. + +- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. + +- Use `mtr` as a better traceroute, to identify network issues. + +- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. + +- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. + +- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. + +- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. + +- Know about `strace` and `ltrace`. 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`). + +- Know about `ldd` to check shared libraries etc. + +- Know how to connect to a running process with `gdb` and get its stack traces. + +- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. + +- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. + +- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). + +- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` + +- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). + + +## 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`. Suppose `a` and `b` are 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 `-T` option if `/tmp` is on a small root partition.) See also the note about `LC_ALL` above and `sort`'s `-u` option (left out for clarity below). +```sh + cat a b | sort | uniq > c # c is a union b + cat a b | sort | uniq -d > c # c is a intersect b + cat a b b | sort | uniq -u > c # c is set difference a - b +``` + +- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/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): +```sh + awk '{ x += $3 } END { print x }' myfile +``` + +- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +```sh + find . -type f -ls +``` + +- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +```sh + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +```sh + cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn +``` + +- Run this function to get a random tip from this document (parses Markdown and extracts an item): +```sh + function taocl() { + curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | + 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 + } +``` + + +## Obscure but useful + +- `expr`: perform arithmetic or boolean operations or evaluate regular expressions + +- `m4`: simple macro processor + +- `yes`: print a string a lot + +- `cal`: nice calendar + +- `env`: run a command (useful in scripts) + +- `printenv`: print out environment variables (useful in debugging and scripts) + +- `look`: find English words (or lines in a file) beginning with a string + +- `cut `and `paste` and `join`: data manipulation + +- `fmt`: format text paragraphs + +- `pr`: format text into pages/columns + +- `fold`: wrap lines of text + +- `column`: format text into columns or tables + +- `expand` and `unexpand`: convert between tabs and spaces + +- `nl`: add line numbers + +- `seq`: print numbers + +- `bc`: calculator + +- `factor`: factor integers + +- `gpg`: encrypt and sign files + +- `toe`: table of terminfo entries + +- `nc`: network debugging and data transfer + +- `socat`: socket relay and tcp port forwarder (similar to `netcat`) + +- `slurm`: network trafic visualization + +- `dd`: moving data between files or devices + +- `file`: identify type of a file + +- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive + +- `stat`: file info + +- `tac`: print files in reverse + +- `shuf`: random selection of lines from a file + +- `comm`: compare sorted files line by line + +- `hd` and `bvi`: dump or edit binary files + +- `strings`: extract text from binary files + +- `tr`: character translation or manipulation + +- `iconv` or `uconv`: conversion for text encodings + +- `split `and `csplit`: splitting files + +- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) + +- `7z`: high-ratio file compression + +- `ldd`: dynamic library info + +- `nm`: symbols from object files + +- `ab`: benchmarking web servers + +- `strace`: system call debugging + +- `mtr`: better traceroute for network debugging + +- `cssh`: visual concurrent shell + +- `rsync`: sync files and folders over SSH + +- `wireshark` and `tshark`: packet capture and network debugging + +- `ngrep`: grep for the network layer + +- `host` and `dig`: DNS lookups + +- `lsof`: process file descriptor and socket info + +- `dstat`: useful system stats + +- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview + +- `iostat`: CPU and disk usage stats + +- `htop`: improved version of top + +- `last`: login history + +- `w`: who's logged on + +- `id`: user/group identity info + +- `sar`: historic system stats + +- `iftop` or `nethogs`: network utilization by socket or process + +- `ss`: socket statistics + +- `dmesg`: boot and system error messages + +- `hdparm`: SATA/ATA disk manipulation/performance + +- `lsb_release`: Linux distribution info + +- `lsblk`: List block devices: a tree view of your disks and disk paritions + +- `lshw`: hardware information + +- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" + + +## More resources + +- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. + + +## 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! ;) + + +## License + +[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) + +This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/). From da6eb66d9515fcbfeca5d647e3d281e1b85f9bee Mon Sep 17 00:00:00 2001 From: Chujie Zeng Date: Thu, 25 Jun 2015 10:55:08 +0800 Subject: [PATCH 09/69] Update README-zh.md Sync with README.md --- README-zh.md | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/README-zh.md b/README-zh.md index 445c08a..c67a0e6 100644 --- a/README-zh.md +++ b/README-zh.md @@ -19,8 +19,7 @@ 这里的大部分内容 [首次](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [出现](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的issue/PR)。 +于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的issue/PR)。 ## 必读 @@ -34,7 +33,7 @@ 注意事项: -- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pip`/`brew` 来安装新程序。 +- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`来安装新程序。 - 使用 [Explainshell](http://explainshell.com/) 去获取相关命令、参数、管道等内容的解释。 @@ -54,13 +53,13 @@ - 了解`ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add`等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解软连接和硬连接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解软连接和硬连接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 - 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 - 熟悉正则表达式,以及`grep`/`egrep`里不同参数的作用,例如`-i`,`-o`,`-A`,和 `-B`。 -- 学会使用`apt-get`,`yum`,或`dnf` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令行工具 (部分程序使用`pip`来安装会很简单)。 +- 学会使用 `apt-get`,`yum`,`dnf` 或 `pacman` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令行工具 (部分程序使用`pip`来安装会很简单)。 ## 日常使用 @@ -117,7 +116,7 @@ - 使用`man ascii`查看具有十六进制和十进制值的ASCII表。`man unicode`,`man utf-8`,以及 `man latin1` 有助于你去了解通用的编码信息。 -- 使用`screen`或`tmux`来使用多个屏幕,当你在使用ssh时(保存session信息)将尤为有用。另一个轻量级的解决方案是`dtach`。 +- 使用`screen`或[`tmux`](https://tmux.github.io/)来使用多个屏幕,当你在使用ssh时(保存session信息)将尤为有用。另一个轻量级的解决方案是`dtach`。 - ssh中,了解如何使用`-L`或`-D`(偶尔需要用`-R`)去开启隧道是非常有用的,例如当你需要从一台远程服务器上访问web。 @@ -165,7 +164,7 @@ - 关于Amazon S3,[`s3cmd`](https://github.com/s3tools/s3cmd)很方便而[`s4cmd`](https://github.com/bloomreach/s4cmd)更快。Amazon官方的[`aws`](https://github.com/aws/aws-cli)是其他AWS相关工作的基础。 -- 了解如何使用`sort`和`uniq`,包括uniq的`-u`参数和`-d`参数,详见后文one-liners。 +- 了解如何使用`sort`和`uniq`,包括uniq的`-u`参数和`-d`参数,详见后文一行代码节。另外可以了解一下`comm`。 - 了解如何使用`cut`,`paste`和`join`来更改文件。大部分人都会使用`cut`但忘了`join`。 @@ -313,6 +312,8 @@ - `env`: 执行一个命令(脚本文件中很有用) +- `printenv`: 打印环境变量(调试时或在使用脚本文件时很有用) + - `look`: 查找以特定字符串开头的单词 - `cut`、`paste`和`join`: 数据修改 @@ -359,7 +360,9 @@ - `comm`: 一行一行的比较排序过的文件 -- `hd`和`bvi`: 保存或编辑二进制文件 +- `pv`: 监视通过管道的数据 + +- `hd` 和 `bvi`: 保存或编辑二进制文件 - `strings`: 从二进制文件中抽取文本 @@ -391,7 +394,7 @@ - `ngrep`: 网络层的grep -- `host`和`dig`: DNS查找 +- `host` 和 `dig`: DNS查找 - `lsof`: 列出当前系统打开文件的工具以及查看端口信息 @@ -411,7 +414,7 @@ - `sar`: 系统历史数据 -- `iftop`或`nethogs`: 套接字及进程的网络利用 +- `iftop` 或 `nethogs`: 套接字及进程的网络利用 - `ss`: 套接字数据 @@ -421,7 +424,9 @@ - `lsb_release`: Linux发行版信息 -- `lshw`: 硬件信息 +- `lsblk`: 列出块设备信息: 以树形展示你的磁盘以及磁盘分区信息 + +- `lshw` 及 `lspci`: 查看硬件信息,包括RAID、显卡等 - `fortune`,`ddate`和`sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" From bb0c38c0899339e836c37eead4a9534b06c56662 Mon Sep 17 00:00:00 2001 From: Raju Vindane Date: Thu, 25 Jun 2015 21:09:11 +0530 Subject: [PATCH 10/69] Just Did a spelling correction with License --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 15cc794..8d9563f 100644 --- a/README.md +++ b/README.md @@ -449,4 +449,4 @@ With the exception of very small tasks, code is written so others can read it. W [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/). +This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From a6f2e01e625acf362a8fb794a24d3f16805e4c34 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 26 Jun 2015 00:30:19 +0300 Subject: [PATCH 11/69] translation(es): section meta. --- README-es.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-es.md b/README-es.md index 6853d97..fd0e964 100644 --- a/README-es.md +++ b/README-es.md @@ -28,15 +28,15 @@ pero debido al interés mostrado ahí, parece que vale la pena usar Github, dond Alcance: -- Esta guía es para ambos el principiante y el experimentado. 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. Many but not all items apply equally to MacOS (or even Cygwin). -- The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting. -- 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. +- Esta guía es para ambos el principiante y el experimentado. Los objetivos son *diversidad* (todo importa), *especificidad* (dar ejemplos concretos del caso más común), y *concisión* (evitar cosas que no son esenciales o insignificantes que puedas buscar facilmente en otro lugar). Cada consejo es esencial en alguna situación o significativamente ahorra tiempo comparada con otras alternativas. +- Esta escrito para Linux. Mucho pero no todos los puntos se aplican igualmente para MacOS (o incluso Cygwin). +- Se enficá en Bash interactivo, Aunque muchos de los consejos se aplican para otros shells y al Bash scripting por lo general. +- Esta incluye ambos comandos "estándar" Unix commands así como aquellos que requiren la instalación especial de in paquete -- siempre que sea suficientemente importante para ameritar su inclusión. -Notes: +Notas: -- 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-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (as appropriate) to install new programs. -- Use [Explainshell](http://explainshell.com/) to get a helpful breakdown of what commands, options, pipes etc. do. +- Para mantener esto en una página, el contenido esta incluido implicitamente por referencia. Tú eres suficientemente inteligente para ver profundamente los detalles en otros lugares, cuando conoces la idea o comando command en Google. Usar `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (según proceda) para instalar los nuevos programas. +- Usar [Explainshell](http://explainshell.com/) para obtener detalles de ayuda sobre que comandos, options, pipes, etc. ## Basics From 967ce7a0e2559971fe885e9196c8b03130976d96 Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Fri, 26 Jun 2015 11:17:29 +0800 Subject: [PATCH 12/69] README-zh.md: Trivial improvements --- README-zh.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README-zh.md b/README-zh.md index c67a0e6..1af12f5 100644 --- a/README-zh.md +++ b/README-zh.md @@ -14,12 +14,12 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -熟练使用命令行是一种常常被忽视或被认为晦涩难懂,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在Linux上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 +熟练使用命令行是一种常常被忽视或被认为难以掌握的技能,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在Linux上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 这里的大部分内容 [首次](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [出现](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的issue/PR)。 +于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的PR/issue)。 ## 必读 @@ -33,7 +33,7 @@ 注意事项: -- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`来安装新程序。 +- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`(以及其它合适的包管理器)来安装新程序。 - 使用 [Explainshell](http://explainshell.com/) 去获取相关命令、参数、管道等内容的解释。 @@ -47,13 +47,13 @@ - 学会使用`>`和`<`来重定向输出和输入,学会使用`|`来重定向管道。了解标准输出stdout和标准错误stderr。 -- 学会使用通配符`*` ( 若能`?`和`{`...`}`更好) 和引用以及引用中`'`和`"`的区别。 +- 学会使用通配符`*` (或许再算上`?`和`{`...`}`) 和引用以及引用中`'`和`"`的区别。 - 熟悉Bash任务管理工具: `&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 - 了解`ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add`等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解软连接和硬连接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 - 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 @@ -150,7 +150,7 @@ - 在当前路径下通过文件名定位一个文件,`find . -iname '*something*'`(或类似的)。在所有路径下通过文件名查找文件,使用 `locate something` (但请记住`updatedb`可能没有对最近新建的文件建立索引)。 -- 使用[`ag`](https://github.com/ggreer/the_silver_searcher)在源或文件里检索(比`grep -r`更好)。 +- 使用[`ag`](https://github.com/ggreer/the_silver_searcher)在源代码或数据文件里检索(比`grep -r`更好)。 - 将HTML转为文本: `lynx -dump -stdin` @@ -158,7 +158,7 @@ - 如果你不得不处理XML,`xmlstarlet`宝刀未老。 -- 使用`jq`处理json。 +- 使用`jq`处理JSON。 - Excel或CSV文件的处理,[csvkit](https://github.com/onyxfish/csvkit)提供了`in2csv`,`csvcut`,`csvjoin`,`csvgrep`等工具。 @@ -166,7 +166,7 @@ - 了解如何使用`sort`和`uniq`,包括uniq的`-u`参数和`-d`参数,详见后文一行代码节。另外可以了解一下`comm`。 -- 了解如何使用`cut`,`paste`和`join`来更改文件。大部分人都会使用`cut`但忘了`join`。 +- 了解如何使用`cut`,`paste`和`join`来更改文件。很多人都会使用`cut`,但几乎都不会使用`join`。 - 了解如何运用`wc`去计算新行数(`-l`),字符数(`-m`),单词数(`-w`)以及字节数(`-c`)。 From 918ddd71c95365a28dfed54dcb66afc68f6104bb Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Fri, 26 Jun 2015 16:58:12 -0300 Subject: [PATCH 13/69] Translate 10% of the text to portugues. #130 --- README-pt.md | 453 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 453 insertions(+) create mode 100644 README-pt.md diff --git a/README-pt.md b/README-pt.md new file mode 100644 index 0000000..a79605a --- /dev/null +++ b/README-pt.md @@ -0,0 +1,453 @@ +[ Languages: [中文](README-zh.md) ] + +# The Art of Command Line + +- [Meta](#meta) +- [Basics](#basics) +- [Everyday use](#everyday-use) +- [Processing files and data](#processing-files-and-data) +- [System debugging](#system-debugging) +- [One-liners](#one-liners) +- [Obscure but useful](#obscure-but-useful) +- [More resources](#more-resources) +- [Disclaimer](#disclaimer) + + +![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) + +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilizada usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você sabe bastante coisas. + +Mais sobre isso +[originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +[appeared](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) +em [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (É claro por favor revise as meta sections e PRs/issues existentes primeiro.) + +## Meta + +Escopo: + +- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *breadth* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais or digressões que vou pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. +- Este guia é escrito para o Linux. Muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). +- O foco está na interatividade no Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. +- Este inclui tanto comandos Unix "padrão", como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. + +Notas: + +- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou siga para o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre comandos, opções, pipes e etc. faz. + + +## Básico + +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). + +- Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). + +- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim builins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. + +- Aprenda a respeito do redirecionamento da saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. + +- Aprenda sobre a expensão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) and quoting and the difference entre aspas duplas `"` e aspas simples `'`. (Veja mais em expansões de variáveis abaixo.) + +- Esteja familiar com o gerenciamento de jobs no Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. + +- Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. + +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), + +- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. + +- Basic network management: `ip` or `ifconfig`, `dig`. + +- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. + +- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). + + +## Everyday use + +- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. + +- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. + +- Alternatively, if you love vi-style key-bindings, use `set -o vi`. + +- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. + +- To go back to the previous working directory: `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. + +- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +```bash + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- `pstree -p` is a helpful display of the process tree. + +- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). + +- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` + +- Use `nohup` or `disown` if you want a background process to keep running forever. + +- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). + +- See also `lsof` for open sockets and files. + +- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. + +- 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 + # 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. + +- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +```sh + diff /etc/hosts <(ssh somehost cat /etc/hosts) +``` + +- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 ` foo: + rename 's/\.bak$//' *.bak + # Full rename of filenames, directories, and contents foo -> bar: + repren --full --preserve-case --from foo --to bar . +``` + +- Use `shuf` to shuffle or select random lines from a file. + +- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `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). + +- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. + +- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. + +- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. + +- For binary diffs (delta compression), use `xdelta3`. + +- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +```sh + 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) and `csplit` (to split by a pattern). + +- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. + + +## System debugging + +- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). + +- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. + +- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. + +- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. + +- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. + +- Use `mtr` as a better traceroute, to identify network issues. + +- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. + +- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. + +- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. + +- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. + +- Know about `strace` and `ltrace`. 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`). + +- Know about `ldd` to check shared libraries etc. + +- Know how to connect to a running process with `gdb` and get its stack traces. + +- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. + +- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. + +- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). + +- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` + +- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). + + +## 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`. Suppose `a` and `b` are 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 `-T` option if `/tmp` is on a small root partition.) See also the note about `LC_ALL` above and `sort`'s `-u` option (left out for clarity below). +```sh + cat a b | sort | uniq > c # c is a union b + cat a b | sort | uniq -d > c # c is a intersect b + cat a b b | sort | uniq -u > c # c is set difference a - b +``` + +- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/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): +```sh + awk '{ x += $3 } END { print x }' myfile +``` + +- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +```sh + find . -type f -ls +``` + +- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +```sh + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +```sh + cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn +``` + +- Run this function to get a random tip from this document (parses Markdown and extracts an item): +```sh + function taocl() { + curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | + 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 + } +``` + + +## Obscure but useful + +- `expr`: perform arithmetic or boolean operations or evaluate regular expressions + +- `m4`: simple macro processor + +- `yes`: print a string a lot + +- `cal`: nice calendar + +- `env`: run a command (useful in scripts) + +- `printenv`: print out environment variables (useful in debugging and scripts) + +- `look`: find English words (or lines in a file) beginning with a string + +- `cut `and `paste` and `join`: data manipulation + +- `fmt`: format text paragraphs + +- `pr`: format text into pages/columns + +- `fold`: wrap lines of text + +- `column`: format text into columns or tables + +- `expand` and `unexpand`: convert between tabs and spaces + +- `nl`: add line numbers + +- `seq`: print numbers + +- `bc`: calculator + +- `factor`: factor integers + +- `gpg`: encrypt and sign files + +- `toe`: table of terminfo entries + +- `nc`: network debugging and data transfer + +- `socat`: socket relay and tcp port forwarder (similar to `netcat`) + +- `slurm`: network trafic visualization + +- `dd`: moving data between files or devices + +- `file`: identify type of a file + +- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive + +- `stat`: file info + +- `tac`: print files in reverse + +- `shuf`: random selection of lines from a file + +- `comm`: compare sorted files line by line + +- `pv`: monitor the progress of data through a pipe + +- `hd` and `bvi`: dump or edit binary files + +- `strings`: extract text from binary files + +- `tr`: character translation or manipulation + +- `iconv` or `uconv`: conversion for text encodings + +- `split `and `csplit`: splitting files + +- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) + +- `7z`: high-ratio file compression + +- `ldd`: dynamic library info + +- `nm`: symbols from object files + +- `ab`: benchmarking web servers + +- `strace`: system call debugging + +- `mtr`: better traceroute for network debugging + +- `cssh`: visual concurrent shell + +- `rsync`: sync files and folders over SSH + +- `wireshark` and `tshark`: packet capture and network debugging + +- `ngrep`: grep for the network layer + +- `host` and `dig`: DNS lookups + +- `lsof`: process file descriptor and socket info + +- `dstat`: useful system stats + +- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview + +- `iostat`: CPU and disk usage stats + +- `htop`: improved version of top + +- `last`: login history + +- `w`: who's logged on + +- `id`: user/group identity info + +- `sar`: historic system stats + +- `iftop` or `nethogs`: network utilization by socket or process + +- `ss`: socket statistics + +- `dmesg`: boot and system error messages + +- `hdparm`: SATA/ATA disk manipulation/performance + +- `lsb_release`: Linux distribution info + +- `lsblk`: List block devices: a tree view of your disks and disk paritions + +- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. + +- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" + + +## More resources + +- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. + + +## 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! ;) + + +## License + +[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) + +This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From eac21107d97c0b1d68aa6dde7e0ea1f6ee00844f Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Sat, 27 Jun 2015 19:37:50 +0800 Subject: [PATCH 14/69] zh: Add more translation --- README-zh.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh.md b/README-zh.md index 1af12f5..8ce4d1a 100644 --- a/README-zh.md +++ b/README-zh.md @@ -53,7 +53,7 @@ - 了解`ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add`等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` and `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 - 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 From 87e5dadc9af58762cb0f384941099200afe65c49 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 09:09:04 -0300 Subject: [PATCH 15/69] Translate 20% of the text. --- README-pt.md | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/README-pt.md b/README-pt.md index a79605a..c7b6905 100644 --- a/README-pt.md +++ b/README-pt.md @@ -54,56 +54,54 @@ Notas: - Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. -- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` and `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versus hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. -- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Gerenciamento básico da rede: `ip` ou `ifconfig`, `dig`. -- Basic network management: `ip` or `ifconfig`, `dig`. +- Sabia bem expressões regulares, e as várias flags para `grep`/`egrep`. As `-i`, `-o`, `-A`, e `-B` são opções que é importante saber. -- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. - -- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). +- Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas abaixo são fáceis de instalar através do `pip`). -## Everyday use +## Usu diário -- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. +- No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. -- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. +- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. *** -- Alternatively, if you love vi-style key-bindings, use `set -o vi`. +- Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. -- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. +- Para ver os comandos recentes, `history`. Existem também muitas abreviações como `!$` (último argumento) e `!!` último comando, embora estes sejam muitas vezes facilmente substituídos por **ctrl-r** e **alt-.**. -- To go back to the previous working directory: `cd -` +- Volte atrás para o diretório de trabalho anterior: `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. +- Se você estar na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Você pode então recuperar o comando mais tarde através do histórico de comandos. -- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- `pstree -p` is a helpful display of the process tree. +- `pstree -p` é um modo de visualização muito útil da árvore de processos. -- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). +- Use `pgrep` e `pkill` para procurar ou sinalizar os processo pelo seu nome (`-f` é muito útil). -- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` +- Saiba os vários sinais que você pode enviar para um processo. Por exemplo, para suspender um processo, use `kill -STOP [pid]`. Para saber a lista completas dos sinais, veja `man 7 signal`. -- Use `nohup` or `disown` if you want a background process to keep running forever. +- Use `nohup` ou `disown` se você deseja por o processo em background executando para sempre. -- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). +- Verifique quais processos estão escutando através `netstat -lntp` ou `ss -plat` (para TCP; adicione `-u` para UDP). -- See also `lsof` for open sockets and files. +- Veja também `lsof` para abrir sockets e arquivos. -- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. +- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` como também, para ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. -- 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. +- Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente mover para um diretório de trabalho diferente, e.g. ```bash - # do something in current dir + # faz algo no diretório corrente (cd /some/other/dir && other-command) - # continue in original dir + # continua no diretório atual ``` - 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. From f14b8edbf76e77639ffa76034a63e6f6bd0c35ee Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 09:45:51 -0300 Subject: [PATCH 16/69] Translate 40% of the text. #130 --- README-pt.md | 138 +++++++++++++++++++++++++-------------------------- 1 file changed, 68 insertions(+), 70 deletions(-) diff --git a/README-pt.md b/README-pt.md index c7b6905..ba95afb 100644 --- a/README-pt.md +++ b/README-pt.md @@ -15,13 +15,13 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilizada usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você sabe bastante coisas. +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui tem bastante conhecimento. Mais sobre isso -[originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) -[appeared](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -em [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (É claro por favor revise as meta sections e PRs/issues existentes primeiro.) +[originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +[apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) +no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta @@ -63,7 +63,7 @@ Notas: - Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas abaixo são fáceis de instalar através do `pip`). -## Usu diário +## Uso diário - No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. @@ -328,123 +328,121 @@ A few examples of piecing together commands: - `column`: format text into columns or tables -- `expand` and `unexpand`: convert between tabs and spaces +- `expand` e `unexpand`: converte entre tabs e espaços. -- `nl`: add line numbers +- `nl`: adiciona números as linhas. -- `seq`: print numbers +- `seq`: imprime números. -- `bc`: calculator +- `bc`: calculadora. -- `factor`: factor integers +- `factor`: fatora inteiros. -- `gpg`: encrypt and sign files +- `gpg`: criptografa e assina arquivos. -- `toe`: table of terminfo entries +- `toe`: tabela de entradas dos tipos de terminais. -- `nc`: network debugging and data transfer +- `nc`: ferramenta de debug de rede e transferência de dados. -- `socat`: socket relay and tcp port forwarder (similar to `netcat`) +- `socat`: socket relay e portas encaminhamento de portas tcp (similar ao `netcat`) -- `slurm`: network trafic visualization +- `slurm`: visualização do tráfego da rede. -- `dd`: moving data between files or devices +- `dd`: move os dados entre arquivos ou dispositivos. -- `file`: identify type of a file +- `file`: identifica o tipo do arquivo. -- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive +- `tree`: mostra os diretórios e subdiretórios como um árvore de dependências; como `ls` mas recursivo. -- `stat`: file info +- `stat`: informações do arquivo. -- `tac`: print files in reverse +- `tac`: imprime arquivos na ordem reversa. -- `shuf`: random selection of lines from a file +- `shuf`: seleção random de linhas de um arquivo. -- `comm`: compare sorted files line by line +- `comm`: compara uma lista de arquivos ordenadas linha por linha. -- `pv`: monitor the progress of data through a pipe +- `pv`: monitora o progresso dos dados através de um pipe. -- `hd` and `bvi`: dump or edit binary files +- `hd` e `bvi`: dump ou edita arquivos binários. -- `strings`: extract text from binary files +- `strings`: extrai texto de arquivos binários. -- `tr`: character translation or manipulation +- `tr`: tradução manipulação de caracteres. -- `iconv` or `uconv`: conversion for text encodings +- `iconv` ou `uconv`: conversor de codificações de text. -- `split `and `csplit`: splitting files +- `split ` e `csplit`: divisão de arquivos. -- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) +- `units`: conversor de unidades e cálculos; converte furlongs por quinzena para twips per blink (veja também `/usr/share/units/definitions.units`) -- `7z`: high-ratio file compression +- `7z`: Compressor de arquivos de alto desempenho. -- `ldd`: dynamic library info +- `ldd`: informações dinâmicas das bibliotecas. -- `nm`: symbols from object files +- `nm`: símbolos de arquivos objetos. -- `ab`: benchmarking web servers +- `ab`: benchmarking para web servers. -- `strace`: system call debugging +- `strace`: Debug para chamadas de sistema. -- `mtr`: better traceroute for network debugging +- `mtr`: melhor tracerout para debugar a rede. -- `cssh`: visual concurrent shell +- `cssh`: Visualização concorrente do shell. -- `rsync`: sync files and folders over SSH +- `rsync`: Sincroniza arquivos e pastas através do SSH. -- `wireshark` and `tshark`: packet capture and network debugging +- `wireshark` e `tshark`: captura de pacotes e debug de rede. -- `ngrep`: grep for the network layer +- `ngrep`: grep para a camada de rede. -- `host` and `dig`: DNS lookups +- `host` e `dig`: Consultas DNS. -- `lsof`: process file descriptor and socket info +- `lsof`: Arquivo de descritores dos processos e informações dos sockets. -- `dstat`: useful system stats +- `dstat`: Estatísticas úteis do sistema. -- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview +- [`glances`](https://github.com/nicolargo/glances): Resumo em alto nível, de multi subsistemas. -- `iostat`: CPU and disk usage stats +- `iostat`: Estatísticas de uso do CPU e do disco. -- `htop`: improved version of top +- `htop`: Versão do top melhorada. -- `last`: login history +- `last`: histórico de logins. -- `w`: who's logged on +- `w`: quem está logado. -- `id`: user/group identity info +- `id`: Informações sobre a identidade do user/group. -- `sar`: historic system stats +- `sar`: histórico dos estados do sistema. -- `iftop` or `nethogs`: network utilization by socket or process +- `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. -- `ss`: socket statistics +- `ss`: Statísticas dos sockets. -- `dmesg`: boot and system error messages +- `dmesg`: Mensagens de erro do sistema e do boot. -- `hdparm`: SATA/ATA disk manipulation/performance +- `hdparm`: Manipulação/performance de discos SATA/ATA. -- `lsb_release`: Linux distribution info +- `lsb_release`: Informações sobre a distribuição do Linux. -- `lsblk`: List block devices: a tree view of your disks and disk paritions +- `lsblk`: Lista os blocos dos dispositivos: uma visualização é forma de árvore dos seus discos e partições do disco. -- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. +- `lshw` e `lspci`: informações do hardware, incluindo RAID, gráficos, etc. -- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" +- `fortune`, `ddate`, e `sl`: um, bem, isto depende de você considerar locomotivas a vapor e citações Zippy "úteis". + +## Mais conteúdo + +- [awesome-shell](https://github.com/alebcay/awesome-shell): Uma lista refinada de ferramentas do shell e outros recursos. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escrever shell scripts melhores. + +## Aviso + +Com a exceção de tarefas muito pequenas, o código é escrito de modo que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) -## More resources - -- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. -- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. - - -## 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! ;) - - -## License +## Licença [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) From 0e95df1ef4dce2b40915fc3d0fd133787f9434f4 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 10:15:13 -0300 Subject: [PATCH 17/69] Translate title and links --- README-pt.md | 19 ++++++++++--------- README.md | 2 ++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/README-pt.md b/README-pt.md index ba95afb..1dbb50c 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,16 +1,17 @@ [ Languages: [中文](README-zh.md) ] +[ Languages: [Portuguese](README-pt.md) ] -# The Art of Command Line +# A arte da linha de comando - [Meta](#meta) -- [Basics](#basics) -- [Everyday use](#everyday-use) -- [Processing files and data](#processing-files-and-data) -- [System debugging](#system-debugging) +- [Básico](#basics) +- [Uso diário](#everyday-use) +- [Processamento de arquivos e dados](#processing-files-and-data) +- [Debugs do sistema](#system-debugging) - [One-liners](#one-liners) -- [Obscure but useful](#obscure-but-useful) -- [More resources](#more-resources) -- [Disclaimer](#disclaimer) +- [Obscuros mas úteis](#obscure-but-useful) +- [Mais conteúdo](#more-resources) +- [Aviso](#disclaimer) ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) @@ -21,7 +22,7 @@ Mais sobre isso [originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro por favor revise as meta sections e PRs/issues existentes primeiro.) +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta diff --git a/README.md b/README.md index 8d9563f..d546670 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ [ Languages: [中文](README-zh.md) ] +[ Languages: [Portuguese](README-pt.md) ] + # The Art of Command Line From 092a4c0d39bb5a5e9b773019a3f63631f3a4142f Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:08:17 -0300 Subject: [PATCH 18/69] Translate 50% of the text. --- README-pt.md | 56 ++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/README-pt.md b/README-pt.md index 1dbb50c..8ece63b 100644 --- a/README-pt.md +++ b/README-pt.md @@ -105,22 +105,22 @@ Notas: # continua no diretório atual ``` -- 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. +- No Bash, note que existem muitos tipos de variáveis de expansão. Verificando a existência de uma variável: `${name:?error_messages}`. Por exemplo, se um script Bash requer um único argumento, apenas escreva `input_file=${1:?usage: $0 input_file}`. Expansões aritméticas: `i=$(( (i + 1) % 5 ))`. Sequências: `{1..10}`. Aparando as strings: `${var%suffix}` e `${var#prefix}`. Por exemplo, se `var=foo.pdf`, então `echo ${var%.pdf}.txt` imprime `foo.txt`. -- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +- A saída de um comando pode ser trata como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 `logfile 2> $1`. Muitas vezes, para garantir que um comando não deixa um arquivo aberto para manipular a entrada padrão, digitando isso no terminal que você está, é uma boa prática adicionar um ` c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/sys`, `/proc`, `/etc`. +- Use `grep . *` para visualmente examinar todo o conteúdo de todos os arquivos de um diretório, por exemplo, para diretórios com arquivos de configurações, como `/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): +- Somar todos os números em uma terceira coluna de um arquivo de texto (isto é provavelmente 3X mais rápido e 3X menos linhas de código do que o equivalente em Python). ```sh awk '{ x += $3 } END { print x }' myfile ``` -- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +- Se você quer visualizar tamanhos/datas em uma árvore de arquivos, isto é como uma `ls -l` recursivo, mas é mais fácil de ler do que `ls -lR`: ```sh find . -type f -ls ``` -- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +- Utilize `xargs` ou `parallel` sempre que você puder. Note que você pode controlar quantos item é executado por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de que esta é a coisa certa a se fazer, utilize `xargs echo` primeiro. ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +- Digamos que você tenha um arquivo de texto, como um log do servidor web, e um certo valor que aparece em algumas linhas, como por exemplo o parâmetro `acct_id` que está presente na URL. Se você quer um cálculo de quantas requisições para este `acct_id`. ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- Run this function to get a random tip from this document (parses Markdown and extracts an item): +- Execute esta função para obter uma dica random deste documento (analisa a sintaxe Markdown e extrai um item) ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | @@ -303,31 +303,31 @@ A few examples of piecing together commands: ``` -## Obscure but useful +## Obscuros mas úteis -- `expr`: perform arithmetic or boolean operations or evaluate regular expressions +- `expr`: executa operações boleanas ou aritméticas ou avalia expressões regulares. -- `m4`: simple macro processor +- `m4`: simples processador de macros. -- `yes`: print a string a lot +- `yes`: imprime uma string muitas vezes. -- `cal`: nice calendar +- `cal`: calendário legal. -- `env`: run a command (useful in scripts) +- `env`: executa um comando (útil em scripts). -- `printenv`: print out environment variables (useful in debugging and scripts) +- `printenv`: imprime as variáveis de ambiente (útil em debug e scripts). -- `look`: find English words (or lines in a file) beginning with a string +- `look`: procura palavras Inglesas (ou linhas em um arquivo) começando com uma string. -- `cut `and `paste` and `join`: data manipulation +- `cut ` e `paste` e `join`: manipulação de dados. -- `fmt`: format text paragraphs +- `fmt`: formata parágrafos de texto. -- `pr`: format text into pages/columns +- `pr`: formata textos em páginas/colunas. -- `fold`: wrap lines of text +- `fold`: envolve linhas de texto. -- `column`: format text into columns or tables +- `column`: formata texto em colunas ou tabelas. - `expand` e `unexpand`: converte entre tabs e espaços. From 05e41b987235f45c0c507385ec46537c562b0fac Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:14:00 -0300 Subject: [PATCH 19/69] Fix links. --- README-pt.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-pt.md b/README-pt.md index 8ece63b..de7a909 100644 --- a/README-pt.md +++ b/README-pt.md @@ -4,14 +4,14 @@ # A arte da linha de comando - [Meta](#meta) -- [Básico](#basics) -- [Uso diário](#everyday-use) -- [Processamento de arquivos e dados](#processing-files-and-data) -- [Debugs do sistema](#system-debugging) +- [Básico](#basico) +- [Uso diário](#uso-diario) +- [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) +- [Debugs do sistema](#debugs-do-sistema) - [One-liners](#one-liners) -- [Obscuros mas úteis](#obscure-but-useful) -- [Mais conteúdo](#more-resources) -- [Aviso](#disclaimer) +- [Obscuros mas úteis](#obscuros-mas-uteis) +- [Mais conteúdo](#mais-conteudo) +- [Aviso](#aviso) ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) From d538d8122264ff153635fb24e06c8c8e008a708a Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:16:43 -0300 Subject: [PATCH 20/69] Fix links. --- README-pt.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README-pt.md b/README-pt.md index de7a909..fe31636 100644 --- a/README-pt.md +++ b/README-pt.md @@ -4,13 +4,13 @@ # A arte da linha de comando - [Meta](#meta) -- [Básico](#basico) -- [Uso diário](#uso-diario) +- [Básico](#básico) +- [Uso diário](#uso-diário) - [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) - [Debugs do sistema](#debugs-do-sistema) - [One-liners](#one-liners) -- [Obscuros mas úteis](#obscuros-mas-uteis) -- [Mais conteúdo](#mais-conteudo) +- [Obscuros mas úteis](#obscuros-mas-úteis) +- [Mais conteúdo](#mais-conteúdo) - [Aviso](#aviso) From c8cec45ff3cc306741ac3829f5adb5caea0b2256 Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Sat, 27 Jun 2015 19:52:47 +0800 Subject: [PATCH 21/69] zh: Add a half-width space between English and Chinese (14%) Completed 14% Re #126 --- README-zh.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README-zh.md b/README-zh.md index 8ce4d1a..629525c 100644 --- a/README-zh.md +++ b/README-zh.md @@ -14,12 +14,12 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -熟练使用命令行是一种常常被忽视或被认为难以掌握的技能,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在Linux上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 +熟练使用命令行是一种常常被忽视或被认为难以掌握的技能,但实际上,它可以提高你作为工程师的灵活性以及生产力。本文是一份我在 Linux 上工作时发现的一些关于命令行的使用的小技巧的摘要。这些小技巧有基础的、相当复杂的甚至晦涩难懂的。这篇文章并不长,但当你能够熟练掌握这里列出的所有技巧时,你就学会了很多关于命令行的东西了。 这里的大部分内容 [首次](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [出现](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用Github来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交Issue或Pull Request!(当然在提交前请看一下必读节和已有的PR/issue)。 +于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用 Github 来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交 Issue 或 Pull Request!(当然在提交前请看一下必读节和已有的 PR/issue)。 ## 必读 @@ -27,9 +27,9 @@ 涵盖范围: - 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为Linux所写,但很多内容(并非所有的)同样适用于MacOS甚至Cygwin。 -- 本文关注于交互式Bash,尽管很多技巧适用于其他shell或Bash脚本。 -- 本文包括了"标准的"Unix命令和需要安装特定包的命令,只要它们足够重要。 +- 本文为 Linux 所写,但很多内容(并非所有的)同样适用于 MacOS 甚至 Cygwin。 +- 本文关注于交互式 Bash,尽管很多技巧适用于其他 shell 或 Bash 脚本。 +- 本文包括了"标准的"Unix 命令和需要安装特定包的命令,只要它们足够重要。 注意事项: @@ -39,27 +39,27 @@ ## 基础 -- 学习Bash的基础知识。具体来说,输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的shell可能很好用,但Bash功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh,fish或其他的shell的话,在你自己的电脑上会显得很方便,但在很多情况下会限制你,比如当你需要在服务器上工作时)。 +- 学习 Bash 的基础知识。具体来说,输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的 shell 可能很好用,但 Bash 功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh,fish 或其他的 shell 的话,在你自己的电脑上会显得很方便,但在很多情况下会限制你,比如当你需要在服务器上工作时)。 - 学习并掌握至少一个基于文本的编辑器。通常 Vim (`vi`) 会是你最好的选择。 -- 学会如何使用`man`命令去阅读文档。学会使用`apropos`去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用`help`和`help -d`命令获取帮助信息。 +- 学会如何使用 `man` 命令去阅读文档。学会使用 `apropos` 去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用 `help` 和 `help -d` 命令获取帮助信息。 -- 学会使用`>`和`<`来重定向输出和输入,学会使用`|`来重定向管道。了解标准输出stdout和标准错误stderr。 +- 学会使用 `>` 和 `<` 来重定向输出和输入,学会使用 `|` 来重定向管道。了解标准输出 stdout 和标准错误 stderr。 -- 学会使用通配符`*` (或许再算上`?`和`{`...`}`) 和引用以及引用中`'`和`"`的区别。 +- 学会使用通配符 `*` (或许再算上 `?` 和 `{`...`}`) 和引用以及引用中 `'` 和 `"` 的区别。 -- 熟悉Bash任务管理工具: `&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 +- 熟悉 Bash 任务管理工具: `&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 -- 了解`ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add`等。 +- 了解 `ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add` 等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解`ls -l`中每一列代表的意义),`less`,`head`,`tail`和`tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解 `ls -l` 中每一列代表的意义),`less`,`head`,`tail` 和 `tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 - 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 -- 熟悉正则表达式,以及`grep`/`egrep`里不同参数的作用,例如`-i`,`-o`,`-A`,和 `-B`。 +- 熟悉正则表达式,以及 `grep`/`egrep` 里不同参数的作用,例如 `-i`,`-o`,`-A`,和 `-B`。 -- 学会使用 `apt-get`,`yum`,`dnf` 或 `pacman` (取决于你使用的Linux发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于Python的命令行工具 (部分程序使用`pip`来安装会很简单)。 +- 学会使用 `apt-get`,`yum`,`dnf` 或 `pacman` (取决于你使用的 Linux 发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于 Python 的命令行工具 (部分程序使用 `pip` 来安装会很简单)。 ## 日常使用 From b949a1e885fbd1e7ad04436f0b24c07c7c9410f2 Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Sat, 27 Jun 2015 22:40:54 +0800 Subject: [PATCH 22/69] zh: Tweak space between English and Chinese text (33%) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finish the "日常使用" section. --- README-zh.md | 54 ++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/README-zh.md b/README-zh.md index 629525c..296d6e3 100644 --- a/README-zh.md +++ b/README-zh.md @@ -64,63 +64,63 @@ ## 日常使用 -- 在Bash中,可以使用**Tab**自动补全参数,使用**ctrl-r**搜索命令行历史。 +- 在 Bash 中,可以使用 **Tab** 自动补全参数,使用 **ctrl-r** 搜索命令行历史。 -- 在Bash中,使用**ctrl-w**删除你键入的最后一个单词,使用**ctrl-u**删除整行,使用**alt-b**和**alt-f**按单词移动,使用**ctrl-k**从光标处删除到行尾,使用**ctrl-l**清屏。键入`man readline`查看Bash中的默认快捷键,内容很多。例如**alt-.** 循环地移向前一个参数,以及**alt-***展开通配符。 +- 在 Bash 中,使用 **ctrl-w** 删除你键入的最后一个单词,使用 **ctrl-u** 删除整行,使用 **alt-b** 和 **alt-f** 按单词移动,使用 **ctrl-k** 从光标处删除到行尾,使用 **ctrl-l** 清屏。键入 `man readline` 查看 Bash 中的默认快捷键,内容很多。例如 **alt-.** 循环地移向前一个参数,以及 **alt-*** 展开通配符。 -- 你喜欢的话,可以键入`set -o vi`来使用vi风格的快捷键。 +- 你喜欢的话,可以键入 `set -o vi` 来使用 vi 风格的快捷键。 -- 键入`history`查看命令行历史记录。其中有许多缩写,例如`!$` (最后键入的参数)和`!!`(最后键入的命令),尽管通常被 **ctrl-r**和**alt-.**取代。 +- 键入 `history` 查看命令行历史记录。其中有许多缩写,例如 `!$`(最后键入的参数)和 `!!`(最后键入的命令),尽管通常被 **ctrl-r** 和 **alt-.** 取代。 - 回到上一个工作路径: `cd -` -- 如果你输入命令的时候改变了主意,按下**alt-#**在行首添加`#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 +- 如果你输入命令的时候改变了主意,按下 **alt-#** 在行首添加 `#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 -- 使用`xargs` ( 或`parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: +- 使用 `xargs` ( 或 `parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- `pstree -p`有助于展示进程树。 +- `pstree -p` 有助于展示进程树。 -- 使用`pgrep`和`pkill`根据名字查找进程或发送信号。 +- 使用 `pgrep` 和 `pkill` 根据名字查找进程或发送信号。 -- 了解你可以发往进程的信号的种类。比如,使用`kill -STOP [pid]`停止一个进程。使用`man 7 signal`查看详细列表。 +- 了解你可以发往进程的信号的种类。比如,使用 `kill -STOP [pid]` 停止一个进程。使用 `man 7 signal` 查看详细列表。 -- 使用`nohup`或`disown`使一个后台进程持续运行。 +- 使用 `nohup` 或 `disown` 使一个后台进程持续运行。 -- 使用`netstat -lntp`或`ss -plat`检查哪些进程在监听端口(默认是检查TCP端口; 使用参数`-u`检查UDP端口)。 +- 使用 `netstat -lntp` 或 `ss -plat` 检查哪些进程在监听端口(默认是检查 TCP 端口; 使用参数 `-u` 检查 UDP 端口)。 -- 有关打开套接字和文件,请参阅`lsof`。 +- 有关打开套接字和文件,请参阅 `lsof`。 -- 在Bash脚本中,使用`set -x`去调试输出,尽可能的使用严格模式,使用`set -e`令脚本在发生错误时退出而不是继续运行,使用`set -o pipefail`严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用`trap`。 +- 在 Bash 脚本中,使用 `set -x` 去调试输出,尽可能的使用严格模式,使用 `set -e` 令脚本在发生错误时退出而不是继续运行,使用 `set -o pipefail` 严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用 `trap`。 -- 在Bash脚本中,子shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: +- 在 Bash 脚本中,子 shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: ```bash # do something in current dir (cd /some/other/dir && other-command) # continue in original dir ``` -- 在Bash中,注意到其中有许多形式的扩展。检查变量是否存在: `${name:?error message}`。例如,当Bash脚本需要一个参数时,可以使用这样的代码`input_file=${1:?usage: $0 input_file}`。数学表达式: `i=$(( (i + 1) % 5 ))`。序列: `{1..10}`。 截断字符串: `${var%suffix}`和`${var#prefix}`。例如,假设`var=foo.pdf`,那么`echo ${var%.pdf}.txt`将输出`foo.txt`。 +- 在 Bash 中,注意到其中有许多形式的扩展。检查变量是否存在: `${name:?error message}`。例如,当 Bash 脚本需要一个参数时,可以使用这样的代码 `input_file=${1:?usage: $0 input_file}`。数学表达式: `i=$(( (i + 1) % 5 ))`。序列: `{1..10}`。 截断字符串: `${var%suffix}` 和 `${var#prefix}`。例如,假设 `var=foo.pdf`,那么 `echo ${var%.pdf}.txt` 将输出 `foo.txt`。 -- 通过使用`<(some command)`可以将输出视为文件。例如,对比本地文件`/etc/hosts`和一个远程文件: +- 通过使用 `<(some command)` 可以将输出视为文件。例如,对比本地文件 `/etc/hosts` 和一个远程文件: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- 了解Bash中的"here documents",例如`cat <logfile 2>&1`。通常,为了保证命令不会在标准输入里残留一个打开了的文件句柄导致你当前所在的终端无法操作,添加`logfile 2>&1`。通常,为了保证命令不会在标准输入里残留一个打开了的文件句柄导致你当前所在的终端无法操作,添加 ` Date: Sat, 27 Jun 2015 11:45:48 -0300 Subject: [PATCH 23/69] Translate 55% of the text --- README-pt.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-pt.md b/README-pt.md index fe31636..c24e2bf 100644 --- a/README-pt.md +++ b/README-pt.md @@ -41,7 +41,7 @@ Notas: ## Básico -- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). - Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). @@ -217,17 +217,17 @@ Notas: - Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. -## System debugging +## Debugando o sistema -- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). +- Para web debug, `curl` e `curl -I` são úteis, ou os equivalentes `wget`, or uma alternativa mais moderna [`httpie`](https://github.com/jakubroztocil/httpie). -- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. +- Para saber o status do disco/cpu/rede, use `iostat`, `netstat`, `top` (ou o `htop` como alternativa melhor), e (especialmente) `dstat`. Bom para obter uma ideia rápida do que está acontecendo em um sistema. -- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. +- Para um resumo mais aprofundado do sistema, use [`glances`](https://github.com/nicolargo/glances). Este lhe apresenta vários níveis de estatísticas do sistema em uma janela do terminal. Muito útil para uma rápida verificação em vários subsistemas. -- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. +- Para saber o status da memória, execute e entenda a saída do `free` `vmstat`. Em particular, esteja ciente de que o valor "cached", é mantido pelo kernel Linux como um arquivo de cache, então este efetivamente conta como um valor de memória disponível. -- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. +- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. - Use `mtr` as a better traceroute, to identify network issues. From ab3e473b62d3d6bbbd228f12c17ea387d3bc3c21 Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Sat, 27 Jun 2015 23:23:17 +0800 Subject: [PATCH 24/69] zh: Tweak space between English and Chinese text (56%) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finish two sections: "文件及数据处理" and "系统调试" --- README-zh.md | 84 ++++++++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/README-zh.md b/README-zh.md index 296d6e3..97f2142 100644 --- a/README-zh.md +++ b/README-zh.md @@ -148,40 +148,40 @@ ## 文件及数据处理 -- 在当前路径下通过文件名定位一个文件,`find . -iname '*something*'`(或类似的)。在所有路径下通过文件名查找文件,使用 `locate something` (但请记住`updatedb`可能没有对最近新建的文件建立索引)。 +- 在当前路径下通过文件名定位一个文件,`find . -iname '*something*'`(或类似的)。在所有路径下通过文件名查找文件,使用 `locate something` (但请记住 `updatedb` 可能没有对最近新建的文件建立索引)。 -- 使用[`ag`](https://github.com/ggreer/the_silver_searcher)在源代码或数据文件里检索(比`grep -r`更好)。 +- 使用 [`ag`](https://github.com/ggreer/the_silver_searcher) 在源代码或数据文件里检索(比 `grep -r` 更好)。 - 将HTML转为文本: `lynx -dump -stdin` - Markdown,HTML,以及所有文档格式之间的转换,试试 [`pandoc`](http://pandoc.org/)。 -- 如果你不得不处理XML,`xmlstarlet`宝刀未老。 +- 如果你不得不处理 XML,`xmlstarlet` 宝刀未老。 -- 使用`jq`处理JSON。 +- 使用 `jq` 处理 JSON。 -- Excel或CSV文件的处理,[csvkit](https://github.com/onyxfish/csvkit)提供了`in2csv`,`csvcut`,`csvjoin`,`csvgrep`等工具。 +- Excel 或 CSV 文件的处理,[csvkit](https://github.com/onyxfish/csvkit) 提供了 `in2csv`,`csvcut`,`csvjoin`,`csvgrep` 等工具。 -- 关于Amazon S3,[`s3cmd`](https://github.com/s3tools/s3cmd)很方便而[`s4cmd`](https://github.com/bloomreach/s4cmd)更快。Amazon官方的[`aws`](https://github.com/aws/aws-cli)是其他AWS相关工作的基础。 +- 关于 Amazon S3,[`s3cmd`](https://github.com/s3tools/s3cmd) 很方便而 [`s4cmd`](https://github.com/bloomreach/s4cmd) 更快。Amazon 官方的 [`aws`](https://github.com/aws/aws-cli) 是其他 AWS 相关工作的基础。 -- 了解如何使用`sort`和`uniq`,包括uniq的`-u`参数和`-d`参数,详见后文一行代码节。另外可以了解一下`comm`。 +- 了解如何使用 `sort` 和 `uniq`,包括 uniq 的 `-u` 参数和 `-d` 参数,详见后文一行代码节。另外可以了解一下 `comm`。 -- 了解如何使用`cut`,`paste`和`join`来更改文件。很多人都会使用`cut`,但几乎都不会使用`join`。 +- 了解如何使用 `cut`,`paste` 和 `join` 来更改文件。很多人都会使用 `cut`,但几乎都不会使用 `join`。 -- 了解如何运用`wc`去计算新行数(`-l`),字符数(`-m`),单词数(`-w`)以及字节数(`-c`)。 +- 了解如何运用 `wc` 去计算新行数(`-l`),字符数(`-m`),单词数(`-w`)以及字节数(`-c`)。 -- 了解如何使用`tee`将标准输入复制到文件甚至标准输出,例如`ls -al | tee file.txt`。 +- 了解如何使用 `tee` 将标准输入复制到文件甚至标准输出,例如 `ls -al | tee file.txt`。 -- 了解语言环境对许多命令行工具的微妙影响,包括排序的顺序和性能。大多数Linux的安装过程会将`LANG`或其他有关的变量设置为符合本地的设置。意识到当你改变语言环境时,排序的结果可能会改变。明白国际化可能会时sort或其他命令运行效率下降*许多倍*。某些情况下(例如集合运算)你可以放心的使用`export LC_ALL=C`来忽略掉国际化并使用基于字节的顺序。 +- 了解语言环境对许多命令行工具的微妙影响,包括排序的顺序和性能。大多数 Linux 的安装过程会将 `LANG` 或其他有关的变量设置为符合本地的设置。意识到当你改变语言环境时,排序的结果可能会改变。明白国际化可能会时 sort 或其他命令运行效率下降*许多倍*。某些情况下(例如集合运算)你可以放心的使用 `export LC_ALL=C` 来忽略掉国际化并使用基于字节的顺序。 -- 了解`awk`和`sed`关于数据的简单处理的用法。例如,将文本文件中第三列的所有数字求和: `awk '{ x += $3 } END { print x }'`. 这可能比同等作用的Python代码块三倍且代码量少三倍。 +- 了解 `awk` 和 `sed` 关于数据的简单处理的用法。例如,将文本文件中第三列的所有数字求和: `awk '{ x += $3 } END { print x }'`. 这可能比同等作用的 Python 代码块三倍且代码量少三倍。 - 替换一个或多个文件中出现的字符串: ```sh perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt ``` -- 依据某种模式批量重命名多个文件,使用`rename`。对于复杂的重命名规则,[`repren`](https://github.com/jlevy/repren)或许有帮助。 +- 依据某种模式批量重命名多个文件,使用 `rename`。对于复杂的重命名规则,[`repren`](https://github.com/jlevy/repren) 或许有帮助。 ```sh # Recover backup files foo.bak -> foo: rename 's/\.bak$//' *.bak @@ -189,69 +189,69 @@ repren --full --preserve-case --from foo --to bar . ``` -- 使用`shuf`从一个文件中随机选取行。 +- 使用 `shuf` 从一个文件中随机选取行。 -- 了解`sort`的参数。明白键的工作原理(`-t`和`-k`)。例如,注意到你需要`-k1,1`来仅按第一个域来排序,而`-k1`意味着按整行排序。 +- 了解 `sort` 的参数。明白键的工作原理(`-t` 和 `-k`)。例如,注意到你需要 `-k1,1` 来仅按第一个域来排序,而 `-k1` 意味着按整行排序。 -- 稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用`sort -k1,1 | sort -s -k2,2` +- 稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用 `sort -k1,1 | sort -s -k2,2` -- 如果你想在Bash命令行中写tab制表符,按下**ctrl-v** **[Tab]** 或键入`$'\t'`(后者可能更好,因为你可以复制粘贴它)。 +- 如果你想在 Bash 命令行中写 tab 制表符,按下 **ctrl-v** **[Tab]** 或键入 `$'\t'` (后者可能更好,因为你可以复制粘贴它)。 -- 标准的源代码对比及合并工具是`diff`和`patch`。使用`diffstat`查看变更总览数据。注意到`diff -r`对整个文件夹有效。使用`diff -r tree1 tree2 | diffstat`查看变更总览数据。 +- 标准的源代码对比及合并工具是 `diff` 和 `patch`。使用 `diffstat` 查看变更总览数据。注意到 `diff -r` 对整个文件夹有效。使用 `diff -r tree1 tree2 | diffstat` 查看变更总览数据。 -- 对于二进制文件,使用`hd`使其以十六进制显示以及使用`bvi`来编辑二进制。 +- 对于二进制文件,使用 `hd` 使其以十六进制显示以及使用 `bvi` 来编辑二进制。 -- 同样对于二进制文件,使用`strings`(包括`grep`等等)允许你查找一些文本。 +- 同样对于二进制文件,使用 `strings`(包括 `grep` 等等)允许你查找一些文本。 -- 二进制文件对比(Delta压缩),使用`xdelta3`。 +- 二进制文件对比(Delta 压缩),使用 `xdelta3`。 -- 使用`iconv`更改文本编码。而更高级的用法,可以使用`uconv`,它支持一些高级的Unicode功能。例如,这条命令将所有元音字母转为小写并移除了: +- 使用 `iconv` 更改文本编码。而更高级的用法,可以使用 `uconv`,它支持一些高级的 Unicode 功能。例如,这条命令将所有元音字母转为小写并移除了: ```sh uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC; ' < input.txt > output.txt ``` -- 拆分文件,查看`split`(按大小拆分)和`csplit`(按模式拆分)。 +- 拆分文件,查看 `split`(按大小拆分)和 `csplit`(按模式拆分)。 -- 使用`zless`,`zmore`,`zcat`和`zgrep`对压缩过的文件进行操作。 +- 使用 `zless`,`zmore`,`zcat` 和 `zgrep`对压缩过的文件进行操作。 ## 系统调试 -- `curl`和`curl -I`可以便捷地被应用于web调试中,它们的好兄弟`wget`也可以,或者是更潮流的[`httpie`](https://github.com/jakubroztocil/httpie)。 +- `curl` 和 `curl -I` 可以便捷地被应用于 web 调试中,它们的好兄弟 `wget` 也可以,或者是更潮流的 [`httpie`](https://github.com/jakubroztocil/httpie)。 -- 使用`iostat`、`netstat`、`top` (`htop`更佳) 和`dstat`去获取硬盘、cpu和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 +- 使用 `iostat`、`netstat`、`top` (`htop` 更佳)和 `dstat` 去获取硬盘、cpu 和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 -- 若要对系统有一个深度的总体认识,使用[`glances`](https://github.com/nicolargo/glances)。它在一个终端窗口中向你提供一些系统级的数据。这对于快速的检查各个子系统非常有帮助。 +- 若要对系统有一个深度的总体认识,使用 [`glances`](https://github.com/nicolargo/glances)。它在一个终端窗口中向你提供一些系统级的数据。这对于快速的检查各个子系统非常有帮助。 -- 若要了解内存状态,运行并理解`free`和`vmstat`的输出。尤其注意"cached"的值,它指的是Linux内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 +- 若要了解内存状态,运行并理解 `free` 和 `vmstat` 的输出。尤其注意"cached"的值,它指的是 Linux 内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 -- Java系统调试则是一件截然不同的事,一个可以用于Oracle的JVM或其他JVM上的调试的小技巧是你可以运行`kill -3 `同时一个完整的栈轨迹和堆概述(包括GC的细节)会被保存到标准输出/日志文件。 +- Java 系统调试则是一件截然不同的事,一个可以用于 Oracle 的 JVM 或其他 JVM 上的调试的小技巧是你可以运行 `kill -3 ` 同时一个完整的栈轨迹和堆概述(包括 GC 的细节)会被保存到标准输出/日志文件。 -- 使用`mtr`去跟踪路由,用于确定网络问题。 +- 使用 `mtr` 去跟踪路由,用于确定网络问题。 -- 用`ncdu`来查看磁盘使用情况,它比常用的命令,如`du -sh *`,更节省时间。 +- 用 `ncdu` 来查看磁盘使用情况,它比常用的命令,如 `du -sh *`,更节省时间。 -- 查找正在使用带宽的套接字连接或进程,使用`iftop`或`nethogs`。 +- 查找正在使用带宽的套接字连接或进程,使用 `iftop` 或 `nethogs`。 -- `ab`工具(捆绑于Apache)可以简单粗暴地检查web服务器的性能。对于更复杂的负载测试,使用`siege`。 +- `ab` 工具(捆绑于 Apache)可以简单粗暴地检查 web 服务器的性能。对于更复杂的负载测试,使用 `siege`。 -- `wireshark`,`tshark`和`ngrep`可用于复杂的网络调试。 +- `wireshark`,`tshark` 和 `ngrep` 可用于复杂的网络调试。 -- 了解`strace`和`ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意profile参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 +- 了解 `strace` 和 `ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意 profile 参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 -- 了解使用`ldd`来检查共享库。 +- 了解使用 `ldd` 来检查共享库。 -- 了解如何运用`gdb`连接到一个运行着的进程并获取它的堆栈轨迹。 +- 了解如何运用 `gdb` 连接到一个运行着的进程并获取它的堆栈轨迹。 -- 学会使用`/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如: `/proc/cpuinfo`,`/proc/xxx/cwd`,`/proc/xxx/exe`,`/proc/xxx/fd/`,`/proc/xxx/smaps`。 +- 学会使用 `/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如: `/proc/cpuinfo`,`/proc/xxx/cwd`,`/proc/xxx/exe`,`/proc/xxx/fd/`,`/proc/xxx/smaps`。 -- 当调试一些之前出现的问题的时候,`sar`非常有用。它展示了cpu、内存以及网络等的历史数据。 +- 当调试一些之前出现的问题的时候,`sar` 非常有用。它展示了 cpu、内存以及网络等的历史数据。 -- 关于更深层次的系统分析以及性能分析,看看`stap` ([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 +- 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 -- 查看你当前使用的Linux发型版(大部分发行版有效): `lsb_release -a` +- 查看你当前使用的 Linux 发型版(大部分发行版有效): `lsb_release -a` -- 无论什么东西工作得很欢乐时试试`dmesg`(可能是硬件或驱动问题)。 +- 无论什么东西工作得很欢乐时试试 `dmesg` (可能是硬件或驱动问题)。 ## 一行代码 From 918e217a36b5796f76f543561710a9f6bcca840f Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Sat, 27 Jun 2015 23:29:03 +0800 Subject: [PATCH 25/69] zh: Tweak space between English and Chinese text (100%) --- README-zh.md | 59 ++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/README-zh.md b/README-zh.md index 97f2142..3419e9b 100644 --- a/README-zh.md +++ b/README-zh.md @@ -258,37 +258,37 @@ 一些命令组合的例子: -- 当你需要对文本文件做集合交、并、差运算时,结合使用`sort`/`uniq`很有帮助。假设`a`与`b`是两内容不同的文件。这种方式效率很高,并且在小文件和上G的文件上都能运用 (`sort`不被内存大小约束,尽管在`/tmp`在一个小的根分区上时你可能需要`-T`参数),参阅前文中关于`LC_ALL`和`sort`的`-u`参数的部分。 +- 当你需要对文本文件做集合交、并、差运算时,结合使用 `sort`/`uniq` 很有帮助。假设 `a` 与 `b` 是两内容不同的文件。这种方式效率很高,并且在小文件和上G的文件上都能运用 (`sort` 不被内存大小约束,尽管在 `/tmp` 在一个小的根分区上时你可能需要 `-T` 参数),参阅前文中关于 `LC_ALL` 和 `sort` 的 `-u` 参数的部分。 ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- 使用`grep . *`来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如`/sys`、`/proc`、`/etc`。 +- 使用 `grep . *` 来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如 `/sys`、`/proc`、`/etc`。 -- 计算文本文件第三列中所有数的和(可能比同等作用的Python代码块三倍且代码量少三倍): +- 计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码块三倍且代码量少三倍): ```sh awk '{ x += $3 } END { print x }' myfile ``` -- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的`ls -l`但比`ls -lR`更易于理解: +- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的 `ls -l` 但比 `ls -lR` 更易于理解: ```sh find . -type f -ls ``` -- 尽可能的使用`xargs`或`parallel`。注意到你可以控制每行参数个数(`-L`)和最大并行数 (`-P`)。如果你不确定它们是否会按你想的那样工作,先使用`xargs echo`查看一下。此外,使用`-I{}`会很方便。例如: +- 尽可能的使用 `xargs` 或 `parallel`。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- 假设你有一个类似于web服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个`acct_id`参数在URI中。如果你想计算出每个`acct_id`值有多少次请求,使用如下代码: +- 假设你有一个类似于 web 服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个 `acct_id` 参数在URI中。如果你想计算出每个 `acct_id` 值有多少次请求,使用如下代码: ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- 运行这个函数从这篇文档中随机获取一条小技巧(解析Markdown文件并抽取项目): +- 运行这个函数从这篇文档中随机获取一条小技巧(解析 Markdown 文件并抽取项目): ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | @@ -316,7 +316,7 @@ - `look`: 查找以特定字符串开头的单词 -- `cut`、`paste`和`join`: 数据修改 +- `cut`、`paste` 和 `join`: 数据修改 - `fmt`: 格式化文本段落 @@ -326,7 +326,7 @@ - `column`: 将文本格式化成多列或表格 -- `expand`和`unexpand`: 制表符与空格之间转换 +- `expand` 和 `unexpand`: 制表符与空格之间转换 - `nl`: 添加行号 @@ -338,11 +338,11 @@ - `gpg`: 加密并签名文件 -- `toe`: terminfo entries列表 +- `toe`: terminfo entries 列表 - `nc`: 网络调试及数据传输 -- `socat`: 套接字代理,与`netcat`类似 +- `socat`: 套接字代理,与 `netcat` 类似 - `slurm`: 网络可视化 @@ -350,7 +350,7 @@ - `file`: 确定文件类型 -- `tree`: 以树的形式显示路径和文件,类似于递归的`ls` +- `tree`: 以树的形式显示路径和文件,类似于递归的 `ls` - `stat`: 文件信息 @@ -368,33 +368,33 @@ - `tr`: 转换字母 -- `iconv`或`uconv`: 简易的文件编码 +- `iconv` 或 `uconv`: 简易的文件编码 -- `split `和`csplit`: 分割文件 +- `split` 和 `csplit`: 分割文件 -- `units`: 将一种计量单位转换为另一种等效的计量单位(参阅`/usr/share/units/definitions.units`) +- `units`: 将一种计量单位转换为另一种等效的计量单位(参阅 `/usr/share/units/definitions.units`) - `7z`: 高比例的文件压缩 - `ldd`: 动态库信息 -- `nm`: 提取obj文件中的符号 +- `nm`: 提取 obj 文件中的符号 -- `ab`: 性能分析web服务器 +- `ab`: 性能分析 web 服务器 - `strace`: 系统调用调试 - `mtr`: 更好的网络调试跟踪工具 -- `cssh`: 可视化的并发shell +- `cssh`: 可视化的并发 shell -- `rsync`: 通过ssh同步文件和文件夹 +- `rsync`: 通过 ssh 同步文件和文件夹 -- `wireshark`和`tshark`:抓包和网络调试工具 +- `wireshark` 和 `tshark`: 抓包和网络调试工具 -- `ngrep`: 网络层的grep +- `ngrep`: 网络层的 grep -- `host` 和 `dig`: DNS查找 +- `host` 和 `dig`: DNS 查找 - `lsof`: 列出当前系统打开文件的工具以及查看端口信息 @@ -402,15 +402,15 @@ - [`glances`](https://github.com/nicolargo/glances): 高层次的多子系统总览 -- `iostat`: CPU和硬盘状态 +- `iostat`: CPU 和硬盘状态 -- `htop`: top的加强版 +- `htop`: top 的加强版 - `last`: 登入记录 - `w`: 查看处于登录状态的用户 -- `id`: 用户/组ID信息 +- `id`: 用户/组 ID 信息 - `sar`: 系统历史数据 @@ -420,15 +420,15 @@ - `dmesg`: 引导及系统错误信息 -- `hdparm`: SATA/ATA磁盘更改及性能分析 +- `hdparm`: SATA/ATA 磁盘更改及性能分析 -- `lsb_release`: Linux发行版信息 +- `lsb_release`: Linux 发行版信息 - `lsblk`: 列出块设备信息: 以树形展示你的磁盘以及磁盘分区信息 -- `lshw` 及 `lspci`: 查看硬件信息,包括RAID、显卡等 +- `lshw` 及 `lspci`: 查看硬件信息,包括 RAID、显卡等 -- `fortune`,`ddate`和`sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" +- `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" ## 更多资源 @@ -447,4 +447,3 @@ [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) 本文使用授权协议 [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/)。 - From 568f3f0d9d966d060ef9101c6feeecab1fb770cd Mon Sep 17 00:00:00 2001 From: Ahmet Alp Balkan Date: Sat, 27 Jun 2015 11:01:24 -0700 Subject: [PATCH 26/69] du -hs instead of -sk --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d9563f..c2885f7 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Notes: - Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc. -- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -hk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. - Basic network management: `ip` or `ifconfig`, `dig`. From ccc3c5ce8e13feacaa1aed3d5ff6094cc2e4e495 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 23:49:17 -0300 Subject: [PATCH 27/69] Translate 95% of the text. #130 --- README-pt.md | 105 ++++++++++++++++++++++++++------------------------- 1 file changed, 53 insertions(+), 52 deletions(-) diff --git a/README-pt.md b/README-pt.md index c24e2bf..370ba02 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,5 @@ [ Languages: [中文](README-zh.md) ] + [ Languages: [Portuguese](README-pt.md) ] # A arte da linha de comando @@ -68,7 +69,7 @@ Notas: - No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. -- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. *** +- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-** expande um glob. - Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. @@ -122,7 +123,7 @@ Notas: - No ssh, saber como realizar um túnel de portas com `-L` ou `-D` (e ocasionalmente `-R`) é útil, para por exemplo acessar sites webs de um servidor remoto. -- It can be useful to make a few optimizations to your ssh configuration; for example, this `~/.ssh/config` contains settings to avoid dropped connections in certain network environments, use compression (which is helpful with scp over low-bandwidth connections), and multiplex channels to the same server with a local control file: +- Pode ser útil realizar algumas otimizações em suas configurações do ssh; por exemplo, o arquivo `~/.ssh/config` contém configurações para evitar que conexões sejam dropadas em certos ambientes de rede, use compressão (muito útil quando se está usando o scp através de uma conexão lenta), e multiplexação de canais do mesmo servidor com um arquivo de controle local: ``` TCPKeepAlive=yes ServerAliveInterval=15 @@ -133,88 +134,88 @@ Notas: 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` +- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam serem habilitadas com cuidado, por exemplo por sub rede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` -- To get the permissions on a file in octal form, which is useful for system configuration but not available in `ls` and easy to bungle, use something like +- Para conseguir as permissões em arquivo em forma octal, o qual é útil para as configurações do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: ```sh stat -c '%A %a %n' /etc/timezone ``` -- For interactive selection of values from the output of another command, use [`percol`](https://github.com/mooz/percol). +- Para seleção interativas de valores da saída de outro comando, use [`percol`](https://github.com/mooz/percol). -- For interaction with files based on the output of another command (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). +- Para interação com arquivos baseados na saída de outro comando (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). -- 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) and `python -m http.server 7777` (for port 7777 and Python 3). +- Para um simples servidor web para todos os arquivos do diretório atual (e subdiretórios), disponível para alguém na sua rede, use: +`python -m SimpleHTTPServer 7777` (para a porta 7777 e Python 2) e `python -m http.server 7777` (para a porta 7777 e Python 3). -## Processing files and data +## Processamento de arquivos e dados -- To locate a file by name in the current directory, `find . -iname '*something*'` (or similar). To find a file anywhere by name, use `locate something` (but bear in mind `updatedb` may not have indexed recently created files). +- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente `updatedb` pode não ter indexado arquivos criados recentemente). -- For general searching through source or data files (more advanced than `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). +- Para uma busca mais geral através de arquivos de dados ou de códigos (mais avançado do que `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). -- To convert HTML to text: `lynx -dump -stdin` +- Para converter HTML para texto: `lynx -dump -stdin`. -- For Markdown, HTML, and all kinds of document conversion, try [`pandoc`](http://pandoc.org/). +- Para Markdown, HTML, e todos os demais tipos de conversão de documentos, tente [`pandoc`](http://pandoc.org/). -- If you must handle XML, `xmlstarlet` is old but good. +- Se você precisa manipular XML, `xmlstarlet` é antigo mas é bom. -- For JSON, use `jq`. +- Para JSON, `jq`. -- For Excel or CSV files, [csvkit](https://github.com/onyxfish/csvkit) provides `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. +- Para Excel ou arquivos CSV, [csvkit](https://github.com/onyxfish/csvkit) que provê `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. -- For Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) is convenient and [`s4cmd`](https://github.com/bloomreach/s4cmd) is faster. Amazon's [`aws`](https://github.com/aws/aws-cli) is essential for other AWS-related tasks. +- Para a Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) é uma forma conveniente e [`s4cmd`](https://github.com/bloomreach/s4cmd) é mais rápido. O [`aws`](https://github.com/aws/aws-cli) da amazon é essencial para outras tarefas relacionadas. -- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. See also `comm`. +- Aprenda a respeito do `sort` e `uniq`, incluindo as opções do `-u` e `-d` do `uniq` -- veja os one-liners abaixo. Veja também `comm`. -- Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`. +- Aprenda a respeito do `cut`, `paste`, e `join` para manipular arquivos de texto. Muitas pessoas usam `cut` mas esquecem do `join`. -- Know about `wc` to count newlines (`-l`), characters (`-m`), words (`-w`) and bytes (`-c`). +- Aprenda a respeito do `wc` para contar novas linhas (`-l`), caracteres (`-m`), palavras (`-m`) e bytes (`-c`). -- Know about `tee` to copy from stdin to a file and also to stdout, as in `ls -al | tee file.txt`. +- Aprenda a respeito do `tee` para copiar da entrada padrão (stdin) para um arquivo e também para a saída padrão (stdout), como no `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 `LANG` or 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, using `export LC_ALL=C`. +- Aprenda que as configurações de localização afetam um várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n oide fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. -- Know basic `awk` and `sed` for simple data munging. For example, summing all numbers in the third column of a text file: `awk '{ x += $3 } END { print x }'`. This is probably 3X faster and 3X shorter than equivalent Python. +- Aprenda o básico sobre `awk` e `sed` para obtenção de informações simples de dados. Por exemplo, somar todos os números na terceira coluna de um arquivo de texto: `awk '{ x += $3 } END { print x }'`. Isto é provavelmente 3X mais rápido e 3X mais curto do que o equivalente em Python. -- To replace all occurrences of a string in place, in one or more files: +- Para substituir todas as ocorrências de uma string em um lugar, em um ou mais arquivos: ```sh perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt ``` -- To rename many files at once according to a pattern, use `rename`. For complex renames, [`repren`](https://github.com/jlevy/repren) may help. +- Para renomear muitos arquivos de uma vez, de acordo com um padrão, use `rename`. Para renomeações mais complexas, [`repren`](https://github.com/jlevy/repren) pode ajudar. ```sh - # Recover backup files foo.bak -> foo: + # Recuperar arquivos de backup foo.bak -> foo: rename 's/\.bak$//' *.bak - # Full rename of filenames, directories, and contents foo -> bar: + # Renomea completamente o nome dos arquivos, diretórios, e outros conteúdos foo -> bar: repren --full --preserve-case --from foo --to bar . ``` -- Use `shuf` to shuffle or select random lines from a file. +- Utilize o `shuf` para embaralhar ou selecionar linhas randoms de um arquivo. -- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means sort according to the whole line. +- Para as opções do `sort`. Aprenda com as chaves (`-t` e `-k`). Em particular, saiba que precisa escrever `-k1,1` para ordenar somente o primeiro campo; `-k1` significa ordenar de acordo com a linha inteira. -- Stable sort (`sort -s`) can be useful. For example, to sort first by field 2, then secondarily by field 1, you can use `sort -k1,1 | sort -s -k2,2` +- Ordenação estável (`sort -s`) pode ser útil. Por exemplo, para ordenar primeiramente pelo campo 2, então secundariamente pelo campo 1, você pode usar `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). +- Se você precisa escrever literalmente um tab na linha de comando no Bash (por exemplo, para o argumento -t do `sort`), pressione **ctrl-v** **[Tab]** ou escreva `$'\t'` (o último é melhor pois você pode copiar e colar ele). -- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. +- As ferramentas padrão para extrair patches de códigos fonte são `diff`e `patch`. Veja também `diffstat` para um resumo de estatísticas de um diff. Note que `diff -r` funciona para diretórios inteiros. Use `diff -r tree1 tree2 | diffstat` para um resumo das alterações. -- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. +- Para arquivos binários, use `hd` para um simples dump hexadecimal e `bvi` para edição binária. -- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. +- Também para arquivos binários, `strings` (mais `grep`, etc.) deixa você encontrar pedaços de texto. -- For binary diffs (delta compression), use `xdelta3`. +- Para diffs binários (compressão delta), use `xdelta3.` -- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +- Para converter a codificação de textos, tente `iconv`. Ou `uconv` para uso mais avançado; Este suporta algumas funcionalidades avançadas do Unicode. Por exemplo, este comando transforma o texto para minúsculo e remove todos os acentos (expandindo e removendo eles): ```sh 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) and `csplit` (to split by a pattern). +- Para dividir um arquivo em pedaços, veja `split` (para dividir por tamanho) e `csplit` (para dividir por um padrão). -- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. +Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. ## Debugando o sistema @@ -229,31 +230,31 @@ Notas: - Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. -- Use `mtr` as a better traceroute, to identify network issues. +- Use `mtr` como um melhor alternativa ao traceroute, para identificar problemas na rede. -- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. +- Para verificar o porque de um disco está cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais com `du -sh *`. -- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. +- Para procurar qual socket ou processo está utilizando a banda de rede, tente `iftop` ou `nethogs`. -- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. +- A ferramenta `ab` (que vem com o Apache) é muito útil para verificação rápida da performance do servidor web. Para mais complexos testes de carga, tente `siege`. -- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. +- Para debugs mais sérios da rede, `wireshark`, `tshark`, or `ngrep`. -- Know about `strace` and `ltrace`. 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`). +- Aprenda a respeito do `strace`e `ltrace`. Estes podem serem úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). -- Know about `ldd` to check shared libraries etc. +- Aprenda a respeito do `ldd` para verificar bibliotecas compartilhadas, e etc. -- Know how to connect to a running process with `gdb` and get its stack traces. +- Aprenda sobre como se contar a um processo em execução com o `gdb` e obter informações sobre a stack trace. -- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. +- Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas vivos. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. -- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. +- Quando estiver debugando o porque de algo ter dado errado no passado, `sar` pode ser de muita utilidade. Este exibe as estatísticas históricas da CPU, memória, rede e etc. -- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). +- Para análises de performance mais profundas do sistema, dê uma olhada em `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), e [`sysdig`](https://github.com/draios/sysdig). -- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` +- Confirme qual a sua distribuição do Linux usando (funciona na maioria das distros): `lsb_release -a`. -- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). +- Use `dmesg` sempre que algo estiver de maneira estranha (isto poderia ser um hardware ou problemas de driver). ## One-liners @@ -447,4 +448,4 @@ Com a exceção de tarefas muito pequenas, o código é escrito de modo que outr [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). +Este trabalho está licenciado sobre uma [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From 626e6d69e524c125183fd06ceffbc45fcfa2268e Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 23:53:42 -0300 Subject: [PATCH 28/69] Fix languages section. --- README-pt.md | 3 +-- README.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README-pt.md b/README-pt.md index 370ba02..93b1996 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,6 +1,5 @@ -[ Languages: [中文](README-zh.md) ] +[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] -[ Languages: [Portuguese](README-pt.md) ] # A arte da linha de comando diff --git a/README.md b/README.md index d546670..81c2521 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -[ Languages: [中文](README-zh.md) ] -[ Languages: [Portuguese](README-pt.md) ] +[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] # The Art of Command Line From aefc01ee7958c04867180ab7e58d430cf6be64b8 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sun, 28 Jun 2015 10:49:19 -0300 Subject: [PATCH 29/69] Translate 100% of the text. Minor improves. #130 --- README-pt.md | 78 ++++++++++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/README-pt.md b/README-pt.md index 93b1996..07eb54e 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,4 @@ -[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] +[ Languages: [English](README.md), [中文](README-zh.md), [Portuguese](README-pt.md)] # A arte da linha de comando @@ -7,7 +7,7 @@ - [Básico](#básico) - [Uso diário](#uso-diário) - [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) -- [Debugs do sistema](#debugs-do-sistema) +- [Debugando o sistema](#debugs-do-sistema) - [One-liners](#one-liners) - [Obscuros mas úteis](#obscuros-mas-úteis) - [Mais conteúdo](#mais-conteúdo) @@ -16,46 +16,46 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui tem bastante conhecimento. +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui bastante conhecimento. Mais sobre isso [originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) +mas dado o interesse lá, então me parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta Escopo: -- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *breadth* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais or digressões que vou pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. -- Este guia é escrito para o Linux. Muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). -- O foco está na interatividade no Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. -- Este inclui tanto comandos Unix "padrão", como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. +- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *generalização* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais ou digressões que você pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. +- Este guia é escrito para o Linux. Porém muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). +- O foco está na interatividade com o Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. +- Este inclui tanto comandos no "padrão" Unix, como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. Notas: -- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou siga para o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. -- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre comandos, opções, pipes e etc. faz. +- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou caso contrário não exite em usar o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre o que faz os comandos, opções, pipes e etc. ## Básico -- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, enquanto é tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). -- Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). +- Aprenda pelo menos um editor baseado em texto bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). -- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim builins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. +- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. - Aprenda a respeito do redirecionamento da saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. -- Aprenda sobre a expensão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) and quoting and the difference entre aspas duplas `"` e aspas simples `'`. (Veja mais em expansões de variáveis abaixo.) +- Aprenda sobre a expansão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) e entendendo as diferenças entre aspas duplas `"` e aspas simples `'`. (Veja mais em variáveis de expansão abaixo.) - Esteja familiar com o gerenciamento de jobs no Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. - Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. -- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` and `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versus hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` e `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versos hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. - Gerenciamento básico da rede: `ip` ou `ifconfig`, `dig`. @@ -76,9 +76,9 @@ Notas: - Volte atrás para o diretório de trabalho anterior: `cd -`. -- Se você estar na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Você pode então recuperar o comando mais tarde através do histórico de comandos. +- Se você está na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Mais tarde você poderá recuperar o comando através do `history`. -- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: +- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza se isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname @@ -96,7 +96,7 @@ Notas: - Veja também `lsof` para abrir sockets e arquivos. -- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` como também, para ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. +- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` para também ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. - Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente mover para um diretório de trabalho diferente, e.g. ```bash @@ -107,7 +107,7 @@ Notas: - No Bash, note que existem muitos tipos de variáveis de expansão. Verificando a existência de uma variável: `${name:?error_messages}`. Por exemplo, se um script Bash requer um único argumento, apenas escreva `input_file=${1:?usage: $0 input_file}`. Expansões aritméticas: `i=$(( (i + 1) % 5 ))`. Sequências: `{1..10}`. Aparando as strings: `${var%suffix}` e `${var#prefix}`. Por exemplo, se `var=foo.pdf`, então `echo ${var%.pdf}.txt` imprime `foo.txt`. -- A saída de um comando pode ser trata como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: +- A saída de um comando pode ser tratada como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` @@ -118,7 +118,7 @@ Notas: - Use `man ascii` para visualizar a tabela ASCII, com valores hexadecimais e decimais. Para informações gerais sobre codificações, `man unicode`, `man utf-8`, e `man latin1` são úteis. -- Use `screen` ou [`tmux`](https://tmux.github.io/) para multiplexar as telas, especialmente útil em sessões ssh remotas e para desanexar e reanexar a uma sessão. Uma alternativa mais simples para a persistência de uma sessão é `dtach`. +- Use `screen` ou [`tmux`](https://tmux.github.io/) para multiplexar as telas, especialmente útil em sessões ssh remotas e para desplugar e replugar a uma sessão. Uma alternativa mais simples para a persistência de uma sessão é `dtach`. - No ssh, saber como realizar um túnel de portas com `-L` ou `-D` (e ocasionalmente `-R`) é útil, para por exemplo acessar sites webs de um servidor remoto. @@ -133,7 +133,7 @@ Notas: ControlPersist yes ``` -- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam serem habilitadas com cuidado, por exemplo por sub rede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` +- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam ser habilitadas com cuidado, por exemplo para subrede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` - Para conseguir as permissões em arquivo em forma octal, o qual é útil para as configurações do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: ```sh @@ -150,7 +150,7 @@ Notas: ## Processamento de arquivos e dados -- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente `updatedb` pode não ter indexado arquivos criados recentemente). +- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente que o `updatedb` pode não ter indexado arquivos criados recentemente). - Para uma busca mais geral através de arquivos de dados ou de códigos (mais avançado do que `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). @@ -174,7 +174,7 @@ Notas: - Aprenda a respeito do `tee` para copiar da entrada padrão (stdin) para um arquivo e também para a saída padrão (stdout), como no `ls -al | tee file.txt`. -- Aprenda que as configurações de localização afetam um várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n oide fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. +- Aprenda que as configurações de localização afetam várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n podem fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. - Aprenda o básico sobre `awk` e `sed` para obtenção de informações simples de dados. Por exemplo, somar todos os números na terceira coluna de um arquivo de texto: `awk '{ x += $3 } END { print x }'`. Isto é provavelmente 3X mais rápido e 3X mais curto do que o equivalente em Python. @@ -227,23 +227,23 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Para saber o status da memória, execute e entenda a saída do `free` `vmstat`. Em particular, esteja ciente de que o valor "cached", é mantido pelo kernel Linux como um arquivo de cache, então este efetivamente conta como um valor de memória disponível. -- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. +- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle ou algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem ser altamente informativos) serão vazados para stderr/logs. -- Use `mtr` como um melhor alternativa ao traceroute, para identificar problemas na rede. +- Use `mtr` como uma melhor alternativa ao traceroute, para identificar problemas na rede. -- Para verificar o porque de um disco está cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais com `du -sh *`. +- Para verificar o porque de um disco estar cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais como `du -sh *`. - Para procurar qual socket ou processo está utilizando a banda de rede, tente `iftop` ou `nethogs`. - A ferramenta `ab` (que vem com o Apache) é muito útil para verificação rápida da performance do servidor web. Para mais complexos testes de carga, tente `siege`. -- Para debugs mais sérios da rede, `wireshark`, `tshark`, or `ngrep`. +- Para debugs mais sérios da rede, `wireshark`, `tshark`, ou `ngrep`. -- Aprenda a respeito do `strace`e `ltrace`. Estes podem serem úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). +- Aprenda a respeito do `strace`e `ltrace`. Estes podem ser úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). - Aprenda a respeito do `ldd` para verificar bibliotecas compartilhadas, e etc. -- Aprenda sobre como se contar a um processo em execução com o `gdb` e obter informações sobre a stack trace. +- Aprenda sobre como se conectar a um processo em execução com o `gdb` e obter informações sobre a stack trace. - Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas vivos. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. @@ -253,14 +253,14 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Confirme qual a sua distribuição do Linux usando (funciona na maioria das distros): `lsb_release -a`. -- Use `dmesg` sempre que algo estiver de maneira estranha (isto poderia ser um hardware ou problemas de driver). +- Use `dmesg` sempre que algo estiver agindo de maneira estranha (isto poderia ser um hardware ou problemas de driver). ## One-liners Alguns exemplos de como reunir os comandos. -- É notavelmente útil algumas vezes, que você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são únicos. Desde modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Ordenação não é limitada por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` a cima es opções `-u` do `sort`(vamos deixar isso claro abaixo). +- É notavelmente útil algumas vezes, que você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são únicos. Desse modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Ordenação não é limitada por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` a cima e as opções `-u` do `sort`(vamos deixar isso claro abaixo). ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b @@ -294,7 +294,7 @@ Alguns exemplos de como reunir os comandos. - Execute esta função para obter uma dica random deste documento (analisa a sintaxe Markdown e extrai um item) ```sh function taocl() { - curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | + curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README-pt.md | pandoc -f markdown -t html | xmlstarlet fo --html --dropdtd | xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" | @@ -345,7 +345,7 @@ Alguns exemplos de como reunir os comandos. - `nc`: ferramenta de debug de rede e transferência de dados. -- `socat`: socket relay e portas encaminhamento de portas tcp (similar ao `netcat`) +- `socat`: socket relay e encaminhamento de portas tcp (similar ao `netcat`) - `slurm`: visualização do tráfego da rede. @@ -369,9 +369,9 @@ Alguns exemplos de como reunir os comandos. - `strings`: extrai texto de arquivos binários. -- `tr`: tradução manipulação de caracteres. +- `tr`: tradução e manipulação de caracteres. -- `iconv` ou `uconv`: conversor de codificações de text. +- `iconv` ou `uconv`: conversor de codificações de texto. - `split ` e `csplit`: divisão de arquivos. @@ -387,7 +387,7 @@ Alguns exemplos de como reunir os comandos. - `strace`: Debug para chamadas de sistema. -- `mtr`: melhor tracerout para debugar a rede. +- `mtr`: melhor traceroute para debugar a rede. - `cssh`: Visualização concorrente do shell. @@ -419,7 +419,7 @@ Alguns exemplos de como reunir os comandos. - `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. -- `ss`: Statísticas dos sockets. +- `ss`: Estatísticas dos sockets. - `dmesg`: Mensagens de erro do sistema e do boot. @@ -427,7 +427,7 @@ Alguns exemplos de como reunir os comandos. - `lsb_release`: Informações sobre a distribuição do Linux. -- `lsblk`: Lista os blocos dos dispositivos: uma visualização é forma de árvore dos seus discos e partições do disco. +- `lsblk`: Lista os blocos dos dispositivos: uma visualização em forma de árvore dos seus discos e partições do disco. - `lshw` e `lspci`: informações do hardware, incluindo RAID, gráficos, etc. @@ -440,7 +440,7 @@ Alguns exemplos de como reunir os comandos. ## Aviso -Com a exceção de tarefas muito pequenas, o código é escrito de modo que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) +Com a exceção de tarefas muito pequenas, o código é escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) ## Licença From c004dac0e068186e4aa46bf13ec1733089e5f04b Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Fri, 26 Jun 2015 16:58:12 -0300 Subject: [PATCH 30/69] Translate 10% of the text to portugues. #130 --- README-pt.md | 453 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 453 insertions(+) create mode 100644 README-pt.md diff --git a/README-pt.md b/README-pt.md new file mode 100644 index 0000000..a79605a --- /dev/null +++ b/README-pt.md @@ -0,0 +1,453 @@ +[ Languages: [中文](README-zh.md) ] + +# The Art of Command Line + +- [Meta](#meta) +- [Basics](#basics) +- [Everyday use](#everyday-use) +- [Processing files and data](#processing-files-and-data) +- [System debugging](#system-debugging) +- [One-liners](#one-liners) +- [Obscure but useful](#obscure-but-useful) +- [More resources](#more-resources) +- [Disclaimer](#disclaimer) + + +![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) + +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilizada usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você sabe bastante coisas. + +Mais sobre isso +[originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +[appeared](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) +em [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (É claro por favor revise as meta sections e PRs/issues existentes primeiro.) + +## Meta + +Escopo: + +- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *breadth* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais or digressões que vou pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. +- Este guia é escrito para o Linux. Muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). +- O foco está na interatividade no Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. +- Este inclui tanto comandos Unix "padrão", como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. + +Notas: + +- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou siga para o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre comandos, opções, pipes e etc. faz. + + +## Básico + +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). + +- Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). + +- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim builins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. + +- Aprenda a respeito do redirecionamento da saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. + +- Aprenda sobre a expensão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) and quoting and the difference entre aspas duplas `"` e aspas simples `'`. (Veja mais em expansões de variáveis abaixo.) + +- Esteja familiar com o gerenciamento de jobs no Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. + +- Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. + +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), + +- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. + +- Basic network management: `ip` or `ifconfig`, `dig`. + +- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. + +- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). + + +## Everyday use + +- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. + +- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. + +- Alternatively, if you love vi-style key-bindings, use `set -o vi`. + +- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. + +- To go back to the previous working directory: `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. + +- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +```bash + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- `pstree -p` is a helpful display of the process tree. + +- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). + +- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` + +- Use `nohup` or `disown` if you want a background process to keep running forever. + +- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). + +- See also `lsof` for open sockets and files. + +- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. + +- 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 + # 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. + +- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +```sh + diff /etc/hosts <(ssh somehost cat /etc/hosts) +``` + +- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 ` foo: + rename 's/\.bak$//' *.bak + # Full rename of filenames, directories, and contents foo -> bar: + repren --full --preserve-case --from foo --to bar . +``` + +- Use `shuf` to shuffle or select random lines from a file. + +- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `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). + +- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. + +- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. + +- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. + +- For binary diffs (delta compression), use `xdelta3`. + +- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +```sh + 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) and `csplit` (to split by a pattern). + +- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. + + +## System debugging + +- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). + +- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. + +- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. + +- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. + +- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. + +- Use `mtr` as a better traceroute, to identify network issues. + +- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. + +- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. + +- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. + +- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. + +- Know about `strace` and `ltrace`. 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`). + +- Know about `ldd` to check shared libraries etc. + +- Know how to connect to a running process with `gdb` and get its stack traces. + +- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. + +- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. + +- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). + +- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` + +- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). + + +## 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`. Suppose `a` and `b` are 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 `-T` option if `/tmp` is on a small root partition.) See also the note about `LC_ALL` above and `sort`'s `-u` option (left out for clarity below). +```sh + cat a b | sort | uniq > c # c is a union b + cat a b | sort | uniq -d > c # c is a intersect b + cat a b b | sort | uniq -u > c # c is set difference a - b +``` + +- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/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): +```sh + awk '{ x += $3 } END { print x }' myfile +``` + +- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +```sh + find . -type f -ls +``` + +- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +```sh + find . -name '*.py' | xargs grep some_function + cat hosts | xargs -I{} ssh root@{} hostname +``` + +- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +```sh + cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn +``` + +- Run this function to get a random tip from this document (parses Markdown and extracts an item): +```sh + function taocl() { + curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | + 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 + } +``` + + +## Obscure but useful + +- `expr`: perform arithmetic or boolean operations or evaluate regular expressions + +- `m4`: simple macro processor + +- `yes`: print a string a lot + +- `cal`: nice calendar + +- `env`: run a command (useful in scripts) + +- `printenv`: print out environment variables (useful in debugging and scripts) + +- `look`: find English words (or lines in a file) beginning with a string + +- `cut `and `paste` and `join`: data manipulation + +- `fmt`: format text paragraphs + +- `pr`: format text into pages/columns + +- `fold`: wrap lines of text + +- `column`: format text into columns or tables + +- `expand` and `unexpand`: convert between tabs and spaces + +- `nl`: add line numbers + +- `seq`: print numbers + +- `bc`: calculator + +- `factor`: factor integers + +- `gpg`: encrypt and sign files + +- `toe`: table of terminfo entries + +- `nc`: network debugging and data transfer + +- `socat`: socket relay and tcp port forwarder (similar to `netcat`) + +- `slurm`: network trafic visualization + +- `dd`: moving data between files or devices + +- `file`: identify type of a file + +- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive + +- `stat`: file info + +- `tac`: print files in reverse + +- `shuf`: random selection of lines from a file + +- `comm`: compare sorted files line by line + +- `pv`: monitor the progress of data through a pipe + +- `hd` and `bvi`: dump or edit binary files + +- `strings`: extract text from binary files + +- `tr`: character translation or manipulation + +- `iconv` or `uconv`: conversion for text encodings + +- `split `and `csplit`: splitting files + +- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) + +- `7z`: high-ratio file compression + +- `ldd`: dynamic library info + +- `nm`: symbols from object files + +- `ab`: benchmarking web servers + +- `strace`: system call debugging + +- `mtr`: better traceroute for network debugging + +- `cssh`: visual concurrent shell + +- `rsync`: sync files and folders over SSH + +- `wireshark` and `tshark`: packet capture and network debugging + +- `ngrep`: grep for the network layer + +- `host` and `dig`: DNS lookups + +- `lsof`: process file descriptor and socket info + +- `dstat`: useful system stats + +- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview + +- `iostat`: CPU and disk usage stats + +- `htop`: improved version of top + +- `last`: login history + +- `w`: who's logged on + +- `id`: user/group identity info + +- `sar`: historic system stats + +- `iftop` or `nethogs`: network utilization by socket or process + +- `ss`: socket statistics + +- `dmesg`: boot and system error messages + +- `hdparm`: SATA/ATA disk manipulation/performance + +- `lsb_release`: Linux distribution info + +- `lsblk`: List block devices: a tree view of your disks and disk paritions + +- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. + +- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" + + +## More resources + +- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. + + +## 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! ;) + + +## License + +[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) + +This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From b801887bc18b894db1ae9af1f8eaa7081982d35d Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 09:09:04 -0300 Subject: [PATCH 31/69] Translate 20% of the text. --- README-pt.md | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/README-pt.md b/README-pt.md index a79605a..c7b6905 100644 --- a/README-pt.md +++ b/README-pt.md @@ -54,56 +54,54 @@ Notas: - Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. -- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` and `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versus hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. -- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Gerenciamento básico da rede: `ip` ou `ifconfig`, `dig`. -- Basic network management: `ip` or `ifconfig`, `dig`. +- Sabia bem expressões regulares, e as várias flags para `grep`/`egrep`. As `-i`, `-o`, `-A`, e `-B` são opções que é importante saber. -- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. - -- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). +- Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas abaixo são fáceis de instalar através do `pip`). -## Everyday use +## Usu diário -- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. +- No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. -- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. +- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. *** -- Alternatively, if you love vi-style key-bindings, use `set -o vi`. +- Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. -- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. +- Para ver os comandos recentes, `history`. Existem também muitas abreviações como `!$` (último argumento) e `!!` último comando, embora estes sejam muitas vezes facilmente substituídos por **ctrl-r** e **alt-.**. -- To go back to the previous working directory: `cd -` +- Volte atrás para o diretório de trabalho anterior: `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. +- Se você estar na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Você pode então recuperar o comando mais tarde através do histórico de comandos. -- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- `pstree -p` is a helpful display of the process tree. +- `pstree -p` é um modo de visualização muito útil da árvore de processos. -- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). +- Use `pgrep` e `pkill` para procurar ou sinalizar os processo pelo seu nome (`-f` é muito útil). -- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` +- Saiba os vários sinais que você pode enviar para um processo. Por exemplo, para suspender um processo, use `kill -STOP [pid]`. Para saber a lista completas dos sinais, veja `man 7 signal`. -- Use `nohup` or `disown` if you want a background process to keep running forever. +- Use `nohup` ou `disown` se você deseja por o processo em background executando para sempre. -- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). +- Verifique quais processos estão escutando através `netstat -lntp` ou `ss -plat` (para TCP; adicione `-u` para UDP). -- See also `lsof` for open sockets and files. +- Veja também `lsof` para abrir sockets e arquivos. -- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. +- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` como também, para ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. -- 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. +- Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente mover para um diretório de trabalho diferente, e.g. ```bash - # do something in current dir + # faz algo no diretório corrente (cd /some/other/dir && other-command) - # continue in original dir + # continua no diretório atual ``` - 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. From 81cdd86df93b75eeac30f271117a0a763c8db9f1 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 09:45:51 -0300 Subject: [PATCH 32/69] Translate 40% of the text. #130 --- README-pt.md | 138 +++++++++++++++++++++++++-------------------------- 1 file changed, 68 insertions(+), 70 deletions(-) diff --git a/README-pt.md b/README-pt.md index c7b6905..ba95afb 100644 --- a/README-pt.md +++ b/README-pt.md @@ -15,13 +15,13 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilizada usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você sabe bastante coisas. +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui tem bastante conhecimento. Mais sobre isso -[originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) -[appeared](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -em [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (É claro por favor revise as meta sections e PRs/issues existentes primeiro.) +[originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +[apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) +no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta @@ -63,7 +63,7 @@ Notas: - Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas abaixo são fáceis de instalar através do `pip`). -## Usu diário +## Uso diário - No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. @@ -328,123 +328,121 @@ A few examples of piecing together commands: - `column`: format text into columns or tables -- `expand` and `unexpand`: convert between tabs and spaces +- `expand` e `unexpand`: converte entre tabs e espaços. -- `nl`: add line numbers +- `nl`: adiciona números as linhas. -- `seq`: print numbers +- `seq`: imprime números. -- `bc`: calculator +- `bc`: calculadora. -- `factor`: factor integers +- `factor`: fatora inteiros. -- `gpg`: encrypt and sign files +- `gpg`: criptografa e assina arquivos. -- `toe`: table of terminfo entries +- `toe`: tabela de entradas dos tipos de terminais. -- `nc`: network debugging and data transfer +- `nc`: ferramenta de debug de rede e transferência de dados. -- `socat`: socket relay and tcp port forwarder (similar to `netcat`) +- `socat`: socket relay e portas encaminhamento de portas tcp (similar ao `netcat`) -- `slurm`: network trafic visualization +- `slurm`: visualização do tráfego da rede. -- `dd`: moving data between files or devices +- `dd`: move os dados entre arquivos ou dispositivos. -- `file`: identify type of a file +- `file`: identifica o tipo do arquivo. -- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive +- `tree`: mostra os diretórios e subdiretórios como um árvore de dependências; como `ls` mas recursivo. -- `stat`: file info +- `stat`: informações do arquivo. -- `tac`: print files in reverse +- `tac`: imprime arquivos na ordem reversa. -- `shuf`: random selection of lines from a file +- `shuf`: seleção random de linhas de um arquivo. -- `comm`: compare sorted files line by line +- `comm`: compara uma lista de arquivos ordenadas linha por linha. -- `pv`: monitor the progress of data through a pipe +- `pv`: monitora o progresso dos dados através de um pipe. -- `hd` and `bvi`: dump or edit binary files +- `hd` e `bvi`: dump ou edita arquivos binários. -- `strings`: extract text from binary files +- `strings`: extrai texto de arquivos binários. -- `tr`: character translation or manipulation +- `tr`: tradução manipulação de caracteres. -- `iconv` or `uconv`: conversion for text encodings +- `iconv` ou `uconv`: conversor de codificações de text. -- `split `and `csplit`: splitting files +- `split ` e `csplit`: divisão de arquivos. -- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) +- `units`: conversor de unidades e cálculos; converte furlongs por quinzena para twips per blink (veja também `/usr/share/units/definitions.units`) -- `7z`: high-ratio file compression +- `7z`: Compressor de arquivos de alto desempenho. -- `ldd`: dynamic library info +- `ldd`: informações dinâmicas das bibliotecas. -- `nm`: symbols from object files +- `nm`: símbolos de arquivos objetos. -- `ab`: benchmarking web servers +- `ab`: benchmarking para web servers. -- `strace`: system call debugging +- `strace`: Debug para chamadas de sistema. -- `mtr`: better traceroute for network debugging +- `mtr`: melhor tracerout para debugar a rede. -- `cssh`: visual concurrent shell +- `cssh`: Visualização concorrente do shell. -- `rsync`: sync files and folders over SSH +- `rsync`: Sincroniza arquivos e pastas através do SSH. -- `wireshark` and `tshark`: packet capture and network debugging +- `wireshark` e `tshark`: captura de pacotes e debug de rede. -- `ngrep`: grep for the network layer +- `ngrep`: grep para a camada de rede. -- `host` and `dig`: DNS lookups +- `host` e `dig`: Consultas DNS. -- `lsof`: process file descriptor and socket info +- `lsof`: Arquivo de descritores dos processos e informações dos sockets. -- `dstat`: useful system stats +- `dstat`: Estatísticas úteis do sistema. -- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview +- [`glances`](https://github.com/nicolargo/glances): Resumo em alto nível, de multi subsistemas. -- `iostat`: CPU and disk usage stats +- `iostat`: Estatísticas de uso do CPU e do disco. -- `htop`: improved version of top +- `htop`: Versão do top melhorada. -- `last`: login history +- `last`: histórico de logins. -- `w`: who's logged on +- `w`: quem está logado. -- `id`: user/group identity info +- `id`: Informações sobre a identidade do user/group. -- `sar`: historic system stats +- `sar`: histórico dos estados do sistema. -- `iftop` or `nethogs`: network utilization by socket or process +- `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. -- `ss`: socket statistics +- `ss`: Statísticas dos sockets. -- `dmesg`: boot and system error messages +- `dmesg`: Mensagens de erro do sistema e do boot. -- `hdparm`: SATA/ATA disk manipulation/performance +- `hdparm`: Manipulação/performance de discos SATA/ATA. -- `lsb_release`: Linux distribution info +- `lsb_release`: Informações sobre a distribuição do Linux. -- `lsblk`: List block devices: a tree view of your disks and disk paritions +- `lsblk`: Lista os blocos dos dispositivos: uma visualização é forma de árvore dos seus discos e partições do disco. -- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. +- `lshw` e `lspci`: informações do hardware, incluindo RAID, gráficos, etc. -- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" +- `fortune`, `ddate`, e `sl`: um, bem, isto depende de você considerar locomotivas a vapor e citações Zippy "úteis". + +## Mais conteúdo + +- [awesome-shell](https://github.com/alebcay/awesome-shell): Uma lista refinada de ferramentas do shell e outros recursos. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escrever shell scripts melhores. + +## Aviso + +Com a exceção de tarefas muito pequenas, o código é escrito de modo que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) -## More resources - -- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. -- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. - - -## 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! ;) - - -## License +## Licença [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) From a735f338df23186b335f7b68a71c48384c29d3c9 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 10:15:13 -0300 Subject: [PATCH 33/69] Translate title and links --- README-pt.md | 19 ++++++++++--------- README.md | 2 ++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/README-pt.md b/README-pt.md index ba95afb..1dbb50c 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,16 +1,17 @@ [ Languages: [中文](README-zh.md) ] +[ Languages: [Portuguese](README-pt.md) ] -# The Art of Command Line +# A arte da linha de comando - [Meta](#meta) -- [Basics](#basics) -- [Everyday use](#everyday-use) -- [Processing files and data](#processing-files-and-data) -- [System debugging](#system-debugging) +- [Básico](#basics) +- [Uso diário](#everyday-use) +- [Processamento de arquivos e dados](#processing-files-and-data) +- [Debugs do sistema](#system-debugging) - [One-liners](#one-liners) -- [Obscure but useful](#obscure-but-useful) -- [More resources](#more-resources) -- [Disclaimer](#disclaimer) +- [Obscuros mas úteis](#obscure-but-useful) +- [Mais conteúdo](#more-resources) +- [Aviso](#disclaimer) ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) @@ -21,7 +22,7 @@ Mais sobre isso [originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro por favor revise as meta sections e PRs/issues existentes primeiro.) +mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta diff --git a/README.md b/README.md index 8d9563f..d546670 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ [ Languages: [中文](README-zh.md) ] +[ Languages: [Portuguese](README-pt.md) ] + # The Art of Command Line From d336e7a77e0ed64d8c9275e5adf7872eaf668d3a Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:08:17 -0300 Subject: [PATCH 34/69] Translate 50% of the text. --- README-pt.md | 56 ++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/README-pt.md b/README-pt.md index 1dbb50c..8ece63b 100644 --- a/README-pt.md +++ b/README-pt.md @@ -105,22 +105,22 @@ Notas: # continua no diretório atual ``` -- 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. +- No Bash, note que existem muitos tipos de variáveis de expansão. Verificando a existência de uma variável: `${name:?error_messages}`. Por exemplo, se um script Bash requer um único argumento, apenas escreva `input_file=${1:?usage: $0 input_file}`. Expansões aritméticas: `i=$(( (i + 1) % 5 ))`. Sequências: `{1..10}`. Aparando as strings: `${var%suffix}` e `${var#prefix}`. Por exemplo, se `var=foo.pdf`, então `echo ${var%.pdf}.txt` imprime `foo.txt`. -- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +- A saída de um comando pode ser trata como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 `logfile 2> $1`. Muitas vezes, para garantir que um comando não deixa um arquivo aberto para manipular a entrada padrão, digitando isso no terminal que você está, é uma boa prática adicionar um ` c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/sys`, `/proc`, `/etc`. +- Use `grep . *` para visualmente examinar todo o conteúdo de todos os arquivos de um diretório, por exemplo, para diretórios com arquivos de configurações, como `/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): +- Somar todos os números em uma terceira coluna de um arquivo de texto (isto é provavelmente 3X mais rápido e 3X menos linhas de código do que o equivalente em Python). ```sh awk '{ x += $3 } END { print x }' myfile ``` -- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +- Se você quer visualizar tamanhos/datas em uma árvore de arquivos, isto é como uma `ls -l` recursivo, mas é mais fácil de ler do que `ls -lR`: ```sh find . -type f -ls ``` -- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +- Utilize `xargs` ou `parallel` sempre que você puder. Note que você pode controlar quantos item é executado por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de que esta é a coisa certa a se fazer, utilize `xargs echo` primeiro. ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +- Digamos que você tenha um arquivo de texto, como um log do servidor web, e um certo valor que aparece em algumas linhas, como por exemplo o parâmetro `acct_id` que está presente na URL. Se você quer um cálculo de quantas requisições para este `acct_id`. ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- Run this function to get a random tip from this document (parses Markdown and extracts an item): +- Execute esta função para obter uma dica random deste documento (analisa a sintaxe Markdown e extrai um item) ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | @@ -303,31 +303,31 @@ A few examples of piecing together commands: ``` -## Obscure but useful +## Obscuros mas úteis -- `expr`: perform arithmetic or boolean operations or evaluate regular expressions +- `expr`: executa operações boleanas ou aritméticas ou avalia expressões regulares. -- `m4`: simple macro processor +- `m4`: simples processador de macros. -- `yes`: print a string a lot +- `yes`: imprime uma string muitas vezes. -- `cal`: nice calendar +- `cal`: calendário legal. -- `env`: run a command (useful in scripts) +- `env`: executa um comando (útil em scripts). -- `printenv`: print out environment variables (useful in debugging and scripts) +- `printenv`: imprime as variáveis de ambiente (útil em debug e scripts). -- `look`: find English words (or lines in a file) beginning with a string +- `look`: procura palavras Inglesas (ou linhas em um arquivo) começando com uma string. -- `cut `and `paste` and `join`: data manipulation +- `cut ` e `paste` e `join`: manipulação de dados. -- `fmt`: format text paragraphs +- `fmt`: formata parágrafos de texto. -- `pr`: format text into pages/columns +- `pr`: formata textos em páginas/colunas. -- `fold`: wrap lines of text +- `fold`: envolve linhas de texto. -- `column`: format text into columns or tables +- `column`: formata texto em colunas ou tabelas. - `expand` e `unexpand`: converte entre tabs e espaços. From fbdbd03c31153b923c6f5045ff7bc085d345e806 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:14:00 -0300 Subject: [PATCH 35/69] Fix links. --- README-pt.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-pt.md b/README-pt.md index 8ece63b..de7a909 100644 --- a/README-pt.md +++ b/README-pt.md @@ -4,14 +4,14 @@ # A arte da linha de comando - [Meta](#meta) -- [Básico](#basics) -- [Uso diário](#everyday-use) -- [Processamento de arquivos e dados](#processing-files-and-data) -- [Debugs do sistema](#system-debugging) +- [Básico](#basico) +- [Uso diário](#uso-diario) +- [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) +- [Debugs do sistema](#debugs-do-sistema) - [One-liners](#one-liners) -- [Obscuros mas úteis](#obscure-but-useful) -- [Mais conteúdo](#more-resources) -- [Aviso](#disclaimer) +- [Obscuros mas úteis](#obscuros-mas-uteis) +- [Mais conteúdo](#mais-conteudo) +- [Aviso](#aviso) ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) From 2c722dc48f6604fc475a9a8296b85da8047e7bf5 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:16:43 -0300 Subject: [PATCH 36/69] Fix links. --- README-pt.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README-pt.md b/README-pt.md index de7a909..fe31636 100644 --- a/README-pt.md +++ b/README-pt.md @@ -4,13 +4,13 @@ # A arte da linha de comando - [Meta](#meta) -- [Básico](#basico) -- [Uso diário](#uso-diario) +- [Básico](#básico) +- [Uso diário](#uso-diário) - [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) - [Debugs do sistema](#debugs-do-sistema) - [One-liners](#one-liners) -- [Obscuros mas úteis](#obscuros-mas-uteis) -- [Mais conteúdo](#mais-conteudo) +- [Obscuros mas úteis](#obscuros-mas-úteis) +- [Mais conteúdo](#mais-conteúdo) - [Aviso](#aviso) From 7e24ef1e7b7cdc46d54cd466928e3b83cf9ae0d1 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 11:45:48 -0300 Subject: [PATCH 37/69] Translate 55% of the text --- README-pt.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-pt.md b/README-pt.md index fe31636..c24e2bf 100644 --- a/README-pt.md +++ b/README-pt.md @@ -41,7 +41,7 @@ Notas: ## Básico -- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). - Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). @@ -217,17 +217,17 @@ Notas: - Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. -## System debugging +## Debugando o sistema -- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). +- Para web debug, `curl` e `curl -I` são úteis, ou os equivalentes `wget`, or uma alternativa mais moderna [`httpie`](https://github.com/jakubroztocil/httpie). -- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. +- Para saber o status do disco/cpu/rede, use `iostat`, `netstat`, `top` (ou o `htop` como alternativa melhor), e (especialmente) `dstat`. Bom para obter uma ideia rápida do que está acontecendo em um sistema. -- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. +- Para um resumo mais aprofundado do sistema, use [`glances`](https://github.com/nicolargo/glances). Este lhe apresenta vários níveis de estatísticas do sistema em uma janela do terminal. Muito útil para uma rápida verificação em vários subsistemas. -- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. +- Para saber o status da memória, execute e entenda a saída do `free` `vmstat`. Em particular, esteja ciente de que o valor "cached", é mantido pelo kernel Linux como um arquivo de cache, então este efetivamente conta como um valor de memória disponível. -- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. +- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. - Use `mtr` as a better traceroute, to identify network issues. From ece99bd2e541f46e877298b1c9763d7785334ed4 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 23:49:17 -0300 Subject: [PATCH 38/69] Translate 95% of the text. #130 --- README-pt.md | 105 ++++++++++++++++++++++++++------------------------- 1 file changed, 53 insertions(+), 52 deletions(-) diff --git a/README-pt.md b/README-pt.md index c24e2bf..370ba02 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,5 @@ [ Languages: [中文](README-zh.md) ] + [ Languages: [Portuguese](README-pt.md) ] # A arte da linha de comando @@ -68,7 +69,7 @@ Notas: - No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. -- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. *** +- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-** expande um glob. - Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. @@ -122,7 +123,7 @@ Notas: - No ssh, saber como realizar um túnel de portas com `-L` ou `-D` (e ocasionalmente `-R`) é útil, para por exemplo acessar sites webs de um servidor remoto. -- It can be useful to make a few optimizations to your ssh configuration; for example, this `~/.ssh/config` contains settings to avoid dropped connections in certain network environments, use compression (which is helpful with scp over low-bandwidth connections), and multiplex channels to the same server with a local control file: +- Pode ser útil realizar algumas otimizações em suas configurações do ssh; por exemplo, o arquivo `~/.ssh/config` contém configurações para evitar que conexões sejam dropadas em certos ambientes de rede, use compressão (muito útil quando se está usando o scp através de uma conexão lenta), e multiplexação de canais do mesmo servidor com um arquivo de controle local: ``` TCPKeepAlive=yes ServerAliveInterval=15 @@ -133,88 +134,88 @@ Notas: 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` +- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam serem habilitadas com cuidado, por exemplo por sub rede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` -- To get the permissions on a file in octal form, which is useful for system configuration but not available in `ls` and easy to bungle, use something like +- Para conseguir as permissões em arquivo em forma octal, o qual é útil para as configurações do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: ```sh stat -c '%A %a %n' /etc/timezone ``` -- For interactive selection of values from the output of another command, use [`percol`](https://github.com/mooz/percol). +- Para seleção interativas de valores da saída de outro comando, use [`percol`](https://github.com/mooz/percol). -- For interaction with files based on the output of another command (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). +- Para interação com arquivos baseados na saída de outro comando (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). -- 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) and `python -m http.server 7777` (for port 7777 and Python 3). +- Para um simples servidor web para todos os arquivos do diretório atual (e subdiretórios), disponível para alguém na sua rede, use: +`python -m SimpleHTTPServer 7777` (para a porta 7777 e Python 2) e `python -m http.server 7777` (para a porta 7777 e Python 3). -## Processing files and data +## Processamento de arquivos e dados -- To locate a file by name in the current directory, `find . -iname '*something*'` (or similar). To find a file anywhere by name, use `locate something` (but bear in mind `updatedb` may not have indexed recently created files). +- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente `updatedb` pode não ter indexado arquivos criados recentemente). -- For general searching through source or data files (more advanced than `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). +- Para uma busca mais geral através de arquivos de dados ou de códigos (mais avançado do que `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). -- To convert HTML to text: `lynx -dump -stdin` +- Para converter HTML para texto: `lynx -dump -stdin`. -- For Markdown, HTML, and all kinds of document conversion, try [`pandoc`](http://pandoc.org/). +- Para Markdown, HTML, e todos os demais tipos de conversão de documentos, tente [`pandoc`](http://pandoc.org/). -- If you must handle XML, `xmlstarlet` is old but good. +- Se você precisa manipular XML, `xmlstarlet` é antigo mas é bom. -- For JSON, use `jq`. +- Para JSON, `jq`. -- For Excel or CSV files, [csvkit](https://github.com/onyxfish/csvkit) provides `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. +- Para Excel ou arquivos CSV, [csvkit](https://github.com/onyxfish/csvkit) que provê `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. -- For Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) is convenient and [`s4cmd`](https://github.com/bloomreach/s4cmd) is faster. Amazon's [`aws`](https://github.com/aws/aws-cli) is essential for other AWS-related tasks. +- Para a Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) é uma forma conveniente e [`s4cmd`](https://github.com/bloomreach/s4cmd) é mais rápido. O [`aws`](https://github.com/aws/aws-cli) da amazon é essencial para outras tarefas relacionadas. -- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. See also `comm`. +- Aprenda a respeito do `sort` e `uniq`, incluindo as opções do `-u` e `-d` do `uniq` -- veja os one-liners abaixo. Veja também `comm`. -- Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`. +- Aprenda a respeito do `cut`, `paste`, e `join` para manipular arquivos de texto. Muitas pessoas usam `cut` mas esquecem do `join`. -- Know about `wc` to count newlines (`-l`), characters (`-m`), words (`-w`) and bytes (`-c`). +- Aprenda a respeito do `wc` para contar novas linhas (`-l`), caracteres (`-m`), palavras (`-m`) e bytes (`-c`). -- Know about `tee` to copy from stdin to a file and also to stdout, as in `ls -al | tee file.txt`. +- Aprenda a respeito do `tee` para copiar da entrada padrão (stdin) para um arquivo e também para a saída padrão (stdout), como no `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 `LANG` or 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, using `export LC_ALL=C`. +- Aprenda que as configurações de localização afetam um várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n oide fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. -- Know basic `awk` and `sed` for simple data munging. For example, summing all numbers in the third column of a text file: `awk '{ x += $3 } END { print x }'`. This is probably 3X faster and 3X shorter than equivalent Python. +- Aprenda o básico sobre `awk` e `sed` para obtenção de informações simples de dados. Por exemplo, somar todos os números na terceira coluna de um arquivo de texto: `awk '{ x += $3 } END { print x }'`. Isto é provavelmente 3X mais rápido e 3X mais curto do que o equivalente em Python. -- To replace all occurrences of a string in place, in one or more files: +- Para substituir todas as ocorrências de uma string em um lugar, em um ou mais arquivos: ```sh perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt ``` -- To rename many files at once according to a pattern, use `rename`. For complex renames, [`repren`](https://github.com/jlevy/repren) may help. +- Para renomear muitos arquivos de uma vez, de acordo com um padrão, use `rename`. Para renomeações mais complexas, [`repren`](https://github.com/jlevy/repren) pode ajudar. ```sh - # Recover backup files foo.bak -> foo: + # Recuperar arquivos de backup foo.bak -> foo: rename 's/\.bak$//' *.bak - # Full rename of filenames, directories, and contents foo -> bar: + # Renomea completamente o nome dos arquivos, diretórios, e outros conteúdos foo -> bar: repren --full --preserve-case --from foo --to bar . ``` -- Use `shuf` to shuffle or select random lines from a file. +- Utilize o `shuf` para embaralhar ou selecionar linhas randoms de um arquivo. -- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means sort according to the whole line. +- Para as opções do `sort`. Aprenda com as chaves (`-t` e `-k`). Em particular, saiba que precisa escrever `-k1,1` para ordenar somente o primeiro campo; `-k1` significa ordenar de acordo com a linha inteira. -- Stable sort (`sort -s`) can be useful. For example, to sort first by field 2, then secondarily by field 1, you can use `sort -k1,1 | sort -s -k2,2` +- Ordenação estável (`sort -s`) pode ser útil. Por exemplo, para ordenar primeiramente pelo campo 2, então secundariamente pelo campo 1, você pode usar `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). +- Se você precisa escrever literalmente um tab na linha de comando no Bash (por exemplo, para o argumento -t do `sort`), pressione **ctrl-v** **[Tab]** ou escreva `$'\t'` (o último é melhor pois você pode copiar e colar ele). -- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. +- As ferramentas padrão para extrair patches de códigos fonte são `diff`e `patch`. Veja também `diffstat` para um resumo de estatísticas de um diff. Note que `diff -r` funciona para diretórios inteiros. Use `diff -r tree1 tree2 | diffstat` para um resumo das alterações. -- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. +- Para arquivos binários, use `hd` para um simples dump hexadecimal e `bvi` para edição binária. -- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. +- Também para arquivos binários, `strings` (mais `grep`, etc.) deixa você encontrar pedaços de texto. -- For binary diffs (delta compression), use `xdelta3`. +- Para diffs binários (compressão delta), use `xdelta3.` -- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +- Para converter a codificação de textos, tente `iconv`. Ou `uconv` para uso mais avançado; Este suporta algumas funcionalidades avançadas do Unicode. Por exemplo, este comando transforma o texto para minúsculo e remove todos os acentos (expandindo e removendo eles): ```sh 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) and `csplit` (to split by a pattern). +- Para dividir um arquivo em pedaços, veja `split` (para dividir por tamanho) e `csplit` (para dividir por um padrão). -- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. +Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. ## Debugando o sistema @@ -229,31 +230,31 @@ Notas: - Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. -- Use `mtr` as a better traceroute, to identify network issues. +- Use `mtr` como um melhor alternativa ao traceroute, para identificar problemas na rede. -- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. +- Para verificar o porque de um disco está cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais com `du -sh *`. -- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. +- Para procurar qual socket ou processo está utilizando a banda de rede, tente `iftop` ou `nethogs`. -- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. +- A ferramenta `ab` (que vem com o Apache) é muito útil para verificação rápida da performance do servidor web. Para mais complexos testes de carga, tente `siege`. -- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. +- Para debugs mais sérios da rede, `wireshark`, `tshark`, or `ngrep`. -- Know about `strace` and `ltrace`. 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`). +- Aprenda a respeito do `strace`e `ltrace`. Estes podem serem úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). -- Know about `ldd` to check shared libraries etc. +- Aprenda a respeito do `ldd` para verificar bibliotecas compartilhadas, e etc. -- Know how to connect to a running process with `gdb` and get its stack traces. +- Aprenda sobre como se contar a um processo em execução com o `gdb` e obter informações sobre a stack trace. -- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. +- Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas vivos. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. -- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. +- Quando estiver debugando o porque de algo ter dado errado no passado, `sar` pode ser de muita utilidade. Este exibe as estatísticas históricas da CPU, memória, rede e etc. -- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). +- Para análises de performance mais profundas do sistema, dê uma olhada em `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), e [`sysdig`](https://github.com/draios/sysdig). -- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` +- Confirme qual a sua distribuição do Linux usando (funciona na maioria das distros): `lsb_release -a`. -- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). +- Use `dmesg` sempre que algo estiver de maneira estranha (isto poderia ser um hardware ou problemas de driver). ## One-liners @@ -447,4 +448,4 @@ Com a exceção de tarefas muito pequenas, o código é escrito de modo que outr [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). +Este trabalho está licenciado sobre uma [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From ecefdf52b9b78f14afe134bc5462e5504d310dc5 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sat, 27 Jun 2015 23:53:42 -0300 Subject: [PATCH 39/69] Fix languages section. --- README-pt.md | 3 +-- README.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README-pt.md b/README-pt.md index 370ba02..93b1996 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,6 +1,5 @@ -[ Languages: [中文](README-zh.md) ] +[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] -[ Languages: [Portuguese](README-pt.md) ] # A arte da linha de comando diff --git a/README.md b/README.md index d546670..81c2521 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -[ Languages: [中文](README-zh.md) ] -[ Languages: [Portuguese](README-pt.md) ] +[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] # The Art of Command Line From 7e05a320c1b9490166d54da6481c6dcbecb8d8ab Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sun, 28 Jun 2015 10:49:19 -0300 Subject: [PATCH 40/69] Translate 100% of the text. Minor improves. #130 --- README-pt.md | 78 ++++++++++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/README-pt.md b/README-pt.md index 93b1996..07eb54e 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,4 @@ -[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] +[ Languages: [English](README.md), [中文](README-zh.md), [Portuguese](README-pt.md)] # A arte da linha de comando @@ -7,7 +7,7 @@ - [Básico](#básico) - [Uso diário](#uso-diário) - [Processamento de arquivos e dados](#processamento-de-arquivos-e-dados) -- [Debugs do sistema](#debugs-do-sistema) +- [Debugando o sistema](#debugs-do-sistema) - [One-liners](#one-liners) - [Obscuros mas úteis](#obscuros-mas-úteis) - [Mais conteúdo](#mais-conteúdo) @@ -16,46 +16,46 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui tem bastante conhecimento. +Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui bastante conhecimento. Mais sobre isso [originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) +mas dado o interesse lá, então me parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) ## Meta Escopo: -- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *breadth* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais or digressões que vou pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. -- Este guia é escrito para o Linux. Muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). -- O foco está na interatividade no Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. -- Este inclui tanto comandos Unix "padrão", como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. +- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *generalização* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais ou digressões que você pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. +- Este guia é escrito para o Linux. Porém muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). +- O foco está na interatividade com o Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. +- Este inclui tanto comandos no "padrão" Unix, como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. Notas: -- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou siga para o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. -- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre comandos, opções, pipes e etc. faz. +- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou caso contrário não exite em usar o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre o que faz os comandos, opções, pipes e etc. ## Básico -- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, é enquanto tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). +- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, enquanto é tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). -- Aprenda pelo menos um editor text-base bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). +- Aprenda pelo menos um editor baseado em texto bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). -- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim builins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. +- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. - Aprenda a respeito do redirecionamento da saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. -- Aprenda sobre a expensão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) and quoting and the difference entre aspas duplas `"` e aspas simples `'`. (Veja mais em expansões de variáveis abaixo.) +- Aprenda sobre a expansão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) e entendendo as diferenças entre aspas duplas `"` e aspas simples `'`. (Veja mais em variáveis de expansão abaixo.) - Esteja familiar com o gerenciamento de jobs no Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. - Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. -- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` and `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versus hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` e `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versos hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. - Gerenciamento básico da rede: `ip` ou `ifconfig`, `dig`. @@ -76,9 +76,9 @@ Notas: - Volte atrás para o diretório de trabalho anterior: `cd -`. -- Se você estar na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Você pode então recuperar o comando mais tarde através do histórico de comandos. +- Se você está na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Mais tarde você poderá recuperar o comando através do `history`. -- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza de isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: +- Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza se isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname @@ -96,7 +96,7 @@ Notas: - Veja também `lsof` para abrir sockets e arquivos. -- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` como também, para ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. +- Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` para também ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. - Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente mover para um diretório de trabalho diferente, e.g. ```bash @@ -107,7 +107,7 @@ Notas: - No Bash, note que existem muitos tipos de variáveis de expansão. Verificando a existência de uma variável: `${name:?error_messages}`. Por exemplo, se um script Bash requer um único argumento, apenas escreva `input_file=${1:?usage: $0 input_file}`. Expansões aritméticas: `i=$(( (i + 1) % 5 ))`. Sequências: `{1..10}`. Aparando as strings: `${var%suffix}` e `${var#prefix}`. Por exemplo, se `var=foo.pdf`, então `echo ${var%.pdf}.txt` imprime `foo.txt`. -- A saída de um comando pode ser trata como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: +- A saída de um comando pode ser tratada como um arquivo através `<(algum comando)`. Por exemplo, comparar um arquivo local `/etc/hosts` com um remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` @@ -118,7 +118,7 @@ Notas: - Use `man ascii` para visualizar a tabela ASCII, com valores hexadecimais e decimais. Para informações gerais sobre codificações, `man unicode`, `man utf-8`, e `man latin1` são úteis. -- Use `screen` ou [`tmux`](https://tmux.github.io/) para multiplexar as telas, especialmente útil em sessões ssh remotas e para desanexar e reanexar a uma sessão. Uma alternativa mais simples para a persistência de uma sessão é `dtach`. +- Use `screen` ou [`tmux`](https://tmux.github.io/) para multiplexar as telas, especialmente útil em sessões ssh remotas e para desplugar e replugar a uma sessão. Uma alternativa mais simples para a persistência de uma sessão é `dtach`. - No ssh, saber como realizar um túnel de portas com `-L` ou `-D` (e ocasionalmente `-R`) é útil, para por exemplo acessar sites webs de um servidor remoto. @@ -133,7 +133,7 @@ Notas: ControlPersist yes ``` -- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam serem habilitadas com cuidado, por exemplo por sub rede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` +- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam ser habilitadas com cuidado, por exemplo para subrede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` - Para conseguir as permissões em arquivo em forma octal, o qual é útil para as configurações do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: ```sh @@ -150,7 +150,7 @@ Notas: ## Processamento de arquivos e dados -- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente `updatedb` pode não ter indexado arquivos criados recentemente). +- Para localizar um arquivo pelo nome no diretório atual, `find . -iname '*something*'` (ou similar). Para procurar um arquivo em qualquer lugar pelo nome, use `locate something` (mas tenha em mente que o `updatedb` pode não ter indexado arquivos criados recentemente). - Para uma busca mais geral através de arquivos de dados ou de códigos (mais avançado do que `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). @@ -174,7 +174,7 @@ Notas: - Aprenda a respeito do `tee` para copiar da entrada padrão (stdin) para um arquivo e também para a saída padrão (stdout), como no `ls -al | tee file.txt`. -- Aprenda que as configurações de localização afetam um várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n oide fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. +- Aprenda que as configurações de localização afetam várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n podem fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. - Aprenda o básico sobre `awk` e `sed` para obtenção de informações simples de dados. Por exemplo, somar todos os números na terceira coluna de um arquivo de texto: `awk '{ x += $3 } END { print x }'`. Isto é provavelmente 3X mais rápido e 3X mais curto do que o equivalente em Python. @@ -227,23 +227,23 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Para saber o status da memória, execute e entenda a saída do `free` `vmstat`. Em particular, esteja ciente de que o valor "cached", é mantido pelo kernel Linux como um arquivo de cache, então este efetivamente conta como um valor de memória disponível. -- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle e algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem serem altamente informativos) serão vazados para stderr/logs. +- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle ou algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem ser altamente informativos) serão vazados para stderr/logs. -- Use `mtr` como um melhor alternativa ao traceroute, para identificar problemas na rede. +- Use `mtr` como uma melhor alternativa ao traceroute, para identificar problemas na rede. -- Para verificar o porque de um disco está cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais com `du -sh *`. +- Para verificar o porque de um disco estar cheio, `ncdu` economiza bastante tempo em comparação aos comandos usuais como `du -sh *`. - Para procurar qual socket ou processo está utilizando a banda de rede, tente `iftop` ou `nethogs`. - A ferramenta `ab` (que vem com o Apache) é muito útil para verificação rápida da performance do servidor web. Para mais complexos testes de carga, tente `siege`. -- Para debugs mais sérios da rede, `wireshark`, `tshark`, or `ngrep`. +- Para debugs mais sérios da rede, `wireshark`, `tshark`, ou `ngrep`. -- Aprenda a respeito do `strace`e `ltrace`. Estes podem serem úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). +- Aprenda a respeito do `strace`e `ltrace`. Estes podem ser úteis se um programa está falhando, travado, ou quebrando, e você não sabe o por que, ou se você quer obter uma ideia geral da performance. Note que a opção de perfil (`-c`), e a habilidade de se plugar a um processo em execução (`-p`). - Aprenda a respeito do `ldd` para verificar bibliotecas compartilhadas, e etc. -- Aprenda sobre como se contar a um processo em execução com o `gdb` e obter informações sobre a stack trace. +- Aprenda sobre como se conectar a um processo em execução com o `gdb` e obter informações sobre a stack trace. - Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas vivos. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. @@ -253,14 +253,14 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Confirme qual a sua distribuição do Linux usando (funciona na maioria das distros): `lsb_release -a`. -- Use `dmesg` sempre que algo estiver de maneira estranha (isto poderia ser um hardware ou problemas de driver). +- Use `dmesg` sempre que algo estiver agindo de maneira estranha (isto poderia ser um hardware ou problemas de driver). ## One-liners Alguns exemplos de como reunir os comandos. -- É notavelmente útil algumas vezes, que você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são únicos. Desde modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Ordenação não é limitada por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` a cima es opções `-u` do `sort`(vamos deixar isso claro abaixo). +- É notavelmente útil algumas vezes, que você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são únicos. Desse modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Ordenação não é limitada por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` a cima e as opções `-u` do `sort`(vamos deixar isso claro abaixo). ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b @@ -294,7 +294,7 @@ Alguns exemplos de como reunir os comandos. - Execute esta função para obter uma dica random deste documento (analisa a sintaxe Markdown e extrai um item) ```sh function taocl() { - curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | + curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README-pt.md | pandoc -f markdown -t html | xmlstarlet fo --html --dropdtd | xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" | @@ -345,7 +345,7 @@ Alguns exemplos de como reunir os comandos. - `nc`: ferramenta de debug de rede e transferência de dados. -- `socat`: socket relay e portas encaminhamento de portas tcp (similar ao `netcat`) +- `socat`: socket relay e encaminhamento de portas tcp (similar ao `netcat`) - `slurm`: visualização do tráfego da rede. @@ -369,9 +369,9 @@ Alguns exemplos de como reunir os comandos. - `strings`: extrai texto de arquivos binários. -- `tr`: tradução manipulação de caracteres. +- `tr`: tradução e manipulação de caracteres. -- `iconv` ou `uconv`: conversor de codificações de text. +- `iconv` ou `uconv`: conversor de codificações de texto. - `split ` e `csplit`: divisão de arquivos. @@ -387,7 +387,7 @@ Alguns exemplos de como reunir os comandos. - `strace`: Debug para chamadas de sistema. -- `mtr`: melhor tracerout para debugar a rede. +- `mtr`: melhor traceroute para debugar a rede. - `cssh`: Visualização concorrente do shell. @@ -419,7 +419,7 @@ Alguns exemplos de como reunir os comandos. - `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. -- `ss`: Statísticas dos sockets. +- `ss`: Estatísticas dos sockets. - `dmesg`: Mensagens de erro do sistema e do boot. @@ -427,7 +427,7 @@ Alguns exemplos de como reunir os comandos. - `lsb_release`: Informações sobre a distribuição do Linux. -- `lsblk`: Lista os blocos dos dispositivos: uma visualização é forma de árvore dos seus discos e partições do disco. +- `lsblk`: Lista os blocos dos dispositivos: uma visualização em forma de árvore dos seus discos e partições do disco. - `lshw` e `lspci`: informações do hardware, incluindo RAID, gráficos, etc. @@ -440,7 +440,7 @@ Alguns exemplos de como reunir os comandos. ## Aviso -Com a exceção de tarefas muito pequenas, o código é escrito de modo que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) +Com a exceção de tarefas muito pequenas, o código é escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) ## Licença From 344c34f10652ac0d4f5772fd987a50bf311fc1ae Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sun, 28 Jun 2015 10:59:05 -0300 Subject: [PATCH 41/69] =?UTF-8?q?Change=20portuguese=20to=20portugu=C3=AAs?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-pt.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README-pt.md b/README-pt.md index 07eb54e..435355c 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [中文](README-zh.md), [Portuguese](README-pt.md)] +[ Languages: [English](README.md), [中文](README-zh.md), [Português](README-pt.md)] # A arte da linha de comando diff --git a/README.md b/README.md index 81c2521..e217f03 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[ Languages: [中文](README-zh.md), [Portuguese](README-pt.md)] +[ Languages: [中文](README-zh.md), [Português](README-pt.md)] # The Art of Command Line From f6e00638e65f72179a3cf1c337809c79fea70af1 Mon Sep 17 00:00:00 2001 From: Nilton Vasques Date: Sun, 28 Jun 2015 11:01:02 -0300 Subject: [PATCH 42/69] Fix glob shortcut. --- README-pt.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-pt.md b/README-pt.md index 435355c..bbc628c 100644 --- a/README-pt.md +++ b/README-pt.md @@ -68,7 +68,7 @@ Notas: - No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. -- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-** expande um glob. +- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. - Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. From 6d59b3cc58bdbc709aeafe50688aec4fb551a1a3 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Sun, 28 Jun 2015 10:16:54 -0700 Subject: [PATCH 43/69] Consistent langauge links. --- README-pt.md | 2 +- README-zh.md | 3 +++ README.md | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/README-pt.md b/README-pt.md index bbc628c..603db7f 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [中文](README-zh.md), [Português](README-pt.md)] +[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] # A arte da linha de comando diff --git a/README-zh.md b/README-zh.md index 1af12f5..701121d 100644 --- a/README-zh.md +++ b/README-zh.md @@ -1,3 +1,6 @@ +[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] + + # 命令行的艺术 - [必读](#必读) diff --git a/README.md b/README.md index e217f03..df3f43d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[ Languages: [中文](README-zh.md), [Português](README-pt.md)] +[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] # The Art of Command Line From 4dad1d191f002ef30d700086d1a9e63b1f2b0b5a Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Sun, 28 Jun 2015 10:49:10 -0700 Subject: [PATCH 44/69] Include lscpu, lsusb, dmidecode. Fixes #136. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df3f43d..1ed67e4 100644 --- a/README.md +++ b/README.md @@ -430,7 +430,7 @@ A few examples of piecing together commands: - `lsblk`: List block devices: a tree view of your disks and disk paritions -- `lshw` and `lspci`: hardware information, including RAID, graphics, etc. +- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: hardware information, including CPU, BIOS, RAID, graphics, devices, etc. - `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" From 0f9b8a74b758992983d362f2e1e1c92a940166ad Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Sun, 28 Jun 2015 10:57:52 -0700 Subject: [PATCH 45/69] Mention sort -h. Fixes #26. --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 7e03a5c..d95f908 100644 --- a/README.md +++ b/README.md @@ -194,9 +194,7 @@ Notes: - Use `shuf` to shuffle or select random lines from a file. -- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `sort -k1,1 | sort -s -k2,2` +- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `sort -k1,1 | sort -s -k2,2`. For handling human-readable numbers (e.g. from `du -h`) use `sort -h`. - 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). From 7ca0135d0e79a1770ad4436d9d719c6698cefc33 Mon Sep 17 00:00:00 2001 From: The Gitter Badger Date: Sun, 28 Jun 2015 18:04:25 +0000 Subject: [PATCH 46/69] Added Gitter badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d95f908..ec29e3c 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ # The Art of Command Line +[![Join the chat at https://gitter.im/jlevy/the-art-of-command-line](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jlevy/the-art-of-command-line?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + - [Meta](#meta) - [Basics](#basics) - [Everyday use](#everyday-use) From ccc23ffb49c2cae3a44108a09e09679a38683bdb Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Sun, 28 Jun 2015 23:48:37 +0300 Subject: [PATCH 47/69] WIP: Basic translated. --- README-es.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README-es.md b/README-es.md index fd0e964..4ece35b 100644 --- a/README-es.md +++ b/README-es.md @@ -1,4 +1,4 @@ -[ Languages: [中文](README-zh.md) [Español](README-es.md) ] +[ Languages: [中文](README-zh.md), [Español](README-es.md) ] # El Arte del Terminal @@ -39,29 +39,29 @@ Notas: - Usar [Explainshell](http://explainshell.com/) para obtener detalles de ayuda sobre que comandos, options, pipes, etc. -## Basics +## Fundamentos -- Learn basic Bash. Actually, type `man bash` and 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). +- Aprenda conocimiento básicos de Bash. De hecho, escriba `man bash` y al menos echelé un vistazo a todo la cosa; Es bastante fácil de seguir y no es tan largo. Alternar entre shells puede ser agradable, pero Bash es poderoso y siempre esta disponible (Por conocimiento *solo* zsh, fish, etc., aunque resulte tentador en tu propia laptop, los restringe en muchas situaciones, tales como el uso de servidores existentes). -- Learn at least one text-based editor well. Ideally Vim (`vi`), as there's really no competition for random editing in a terminal (even if you use Emacs, a big IDE, or a modern hipster editor most of the time). +- Aprenda almenos un editor de texto bien. Idealmente Vim (`vi`), como no hay realmente una competencia para la edción aleatorea en un terminal (incluso si usted usa Emacs, un gran IDE, o un editor alternativo (hipster) moderno la mayor parte del tiempo). -- Know how to read documentation with `man` (for the inquisitive, `man man` lists the section numbers, e.g. 1 is "regular" commands, 5 is files/conventions, and 8 are for administration). Find man pages with `apropos`. Know that some commands are not executables, but Bash builtins, and that you can get help on them with `help` and `help -d`. +- Conozca como leer la documentation con `man` (Para curiosos, `man man` lista las secciones enumeradas, ej. 1 es comandos "regulares", 5 son archivos/convenciones, y 8 are para administración). En en las páginas de man `apropos`. Conozca que alguno de los comandos no son ejecutables, paro son Bash builtins, y que ouede obtener ayuda sobre ellos con `help` y `help -d`. -- Learn about redirection of output and input using `>` and `<` and pipes using `|`. Learn about stdout and stderr. +- Aprenda sobre redirección de salida y entrada `>` y `<` and pipes utilizando `|`. Aprenda sobre stdout y 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.) +- Aprenda sobre expansión de archivos glob con `*` (y tal vez `?` y `{`...`}`) y quoting y la diferencia entre doble `"` y simple `'` quotes. (Ver mas en expansión variable más abajo.) -- Be familiar with Bash job management: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. +- Familiarizate con administración de trabajo en Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. -- Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc. +- Conoce `ssh`, y lo básico de authenticacion sin password, via `ssh-agent`, `ssh-add`, etc. -- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -sk *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Adminisración de archivos básica: `ls` y `ls -l` (en particular, aprenda el significado de cada columna in `ls -l`), `less`, `head`, `tail` y `tail -f` (o incluso mejor, `less +F`), `ln` y `ln -s` (aprenda las diferencias y ventajas entre hard y soft links), `chown`, `chmod`, `du` (para un rápido resumen del uso del disco: `du -sk *`). Para administración de filesystem, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. -- Basic network management: `ip` or `ifconfig`, `dig`. +- Administración de redes básico: `ip` o `ifconfig`, `dig`. -- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-A`, and `-B` options are worth knowing. +- Conozca expresiones regulares bien, y varias banderas (flags) para `grep`/`egrep`. El `-i`, `-o`, `-A`, y `-B` son opciones dignas de ser conocidas. -- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`). +- Aprenda el uso de `apt-get`, `yum`, `dnf` o `pacman` (dependiendo de la dismtribución "distro") para buscar e instalar paquetes. Y asegurate que tienes `pip` para instalar la herramienta de linea de comando basada en Python (un poco más abajo esta super fácil para instalar vía `pip`). ## Everyday use From 0eda62b951275a2a04c21b9ab5476cd6258191cb Mon Sep 17 00:00:00 2001 From: Valeria de Paiva Date: Sun, 28 Jun 2015 20:06:06 -0700 Subject: [PATCH 48/69] Update README-pt.md --- README-pt.md | 59 ++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/README-pt.md b/README-pt.md index 603db7f..43b46f2 100644 --- a/README-pt.md +++ b/README-pt.md @@ -16,67 +16,66 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -Fluência na linha de comando é uma skill muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como um *desenvolvedor*. Este texto descreve uma selação de notas e dicas de uso da linha de comando que eu tenho encontrado muita utilidade usando o Linux. Algumas dicas são elementares, e algumas são mais específicas, sofisticadas ou obscuras. Esta página não é tão longa, mas se você puder usar e relembrar todos os items que estão aqui, então você possui bastante conhecimento. +Fluência na linha de comando é uma habilidade muitas vezes negligenciada ou considerada obsoleta, porém ela aumenta sua flexibilidade e produtividade como *desenvolvedor* de diversas maneiras, sutis ou não. Este texto descreve uma seleção de notas e dicas de uso da linha de comando que me parecem muito uteis, quando usando o Linux. Algumas dicas são elementares, e outras são mais específicas, sofisticadas ou obscuras. Esta página é curta, mas se você souber usar e lembrar todos os items que estão aqui, então você está mandando bem. -Mais sobre isso -[originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) +Muito do que está aqui [originalmente](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [apareceu](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) no [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), -mas dado o interesse lá, então me parece que é importante usar o Github, onde pessoas mais talentosas do que eu, prontamente podem sugerir melhorias. Se você ver um erro ou algo que poderia ser melhorado, por favor abra uma issue ou um PR! (E claro, por favor revise as meta sections e PRs/issues existentes primeiro.) +mas dado o interesse por lá, me pareceu importante usar o Github, onde pessoas mais talentosas do que eu, poderiam sugerir melhorias facilmente. Se você descobrir um erro ou algo que poderia ser melhorado, por favor abra um issue ou um PR! (E claro, por favor veja as `meta sections' e PRs/issues existentes, primeiro.) ## Meta Escopo: -- Este guia é destinado tanto para iniciantes como para usuários mais experientes. Os objetivos são *generalização* (tudo de importante), *aprofundamento* (dar exemplos concretos dos casos de uso mais comuns), e *brevidade* (evitar coisas que não são tão essenciais ou digressões que você pode facilmente encontrar por aí). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. -- Este guia é escrito para o Linux. Porém muitos, mas não todos os items se aplicam igualmente para o MacOS (ou mesmo o Cygwin). -- O foco está na interatividade com o Bash, embora muitas dicas aqui são aplicadas para outros shells e em geral para Bash script. -- Este inclui tanto comandos no "padrão" Unix, como comandos que requerem instalação de pacotes adicionais -- tanto quanto estes sejam importantes o suficiente para merecerem sua inclusão. +- Este guia é destinado tanto aos iniciantes quanto aos usuários mais experientes. Os objetivos são *abrangencia* (tudo que é importante), *especificidade* (dar exemplos concretos dos casos de usos mais comuns), e *brevidade* (evitar coisas que não são tão essenciais ou digressões que você pode facilmente encontrar pela internet). Todas as dicas são essenciais em alguma situação ou trazem uma economia notável de tempo em relação a outras alternativas. +- Este guia é escrito para o Linux. Muitos, mas não todos os items, se aplicam igualmente para o MacOS (ou mesmo o Cygwin). +- O foco está na interatividade com Bash, embora muitas dicas aqui sejam aplicáveis a outras `shells' e tambem a scripts em Bash, em geral. +- Incluimos tanto comandos no Unix "padrão", quanto comandos que requeiram instalação de pacotes adicionais -- desde que estes sejam importantes o suficiente para merecerem sua inclusão nessa lista. Notas: -- Para manter este guia em uma página, o conteúdo implícito será incluído por referência. Você é experto o suficiente para verificar mais detalhes em outros lugares, uma vez que você já tenha entendido a ideia ou caso contrário não exite em usar o Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (como adequado) para instalar novos programas. -- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre o que faz os comandos, opções, pipes e etc. +- Para manter este guia em uma única página, o conteúdo implícito será incluído por referência. Você é competente o suficiente para verificar mais detalhes em outros lugares, desde que você já tenha entendido a ideia ou saiba o que procurar no Google. Use `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (quando adequado) para instalar novos programas. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre o que fazem os comandos, as opções, pipes e etc. ## Básico -- Aprenda o básico sobre Bash. Atualmente, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativos podem serem legais, mas o Bash é mais poderoso e sempre estar disponível (aprendendo *somente* zsh, fish, etc, enquanto é tentador no seu próprio notebook, restringe você em muitas situações, como ao usar servidores existentes). +- Aprenda o básico sobre Bash. Na verdade, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativas podem ser legais, mas Bash é a mais poderosa e sempre está disponível (aprender *somente* zsh, fish, etc, é tentador quando voce usa o seu próprio laptop, mas restringe você em muitas situações, por exemplo quando você quer usar servidores de outros). -- Aprenda pelo menos um editor baseado em texto bem. Idealmente o Vim (`vi`), como não existe nenhuma competição aleatória de edição em um terminal ( mesmo se você usa o Emacs, uma grande IDE, ou um moderno editor hipster a maioria do tempo). +- Aprenda bem pelo menos um editor de text tradicional. Idealmente o Vim (`vi`), já que nenhum outro funciona tão bem nos terminais aleatorios que a gente encontra por ai (mesmo que você prefira usar o Emacs, um IDE, ou um editor hipster a maior parte do tempo). -- Saiba como ler a documentação com o `man` (por curiosidade, `man man` lista os números das seções, exemplo. 1 se refere aos comandos "regular", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outras documentos do man com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, os quais você poderá conseguir ajuda com `help` e `help -d`. +- Saiba como ler a documentação com o `man` (para os curiosos, `man man` lista os números das seções, por exemplo, 1 se refere aos comandos "regulares", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outros documentos do manual com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, pra esses você poderá conseguir ajuda com `help` e `help -d`. -- Aprenda a respeito do redirecionamento da saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. +- Aprenda como fazer redirecionamento de saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. -- Aprenda sobre a expansão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) e entendendo as diferenças entre aspas duplas `"` e aspas simples `'`. (Veja mais em variáveis de expansão abaixo.) +- Aprenda sobre a expansão de arquivos glob com `*` ( e talvez `?` e `{`...`}`) e entenda as diferenças entre aspas duplas `"` e aspas simples `'`. (Veja mais em variáveis de expansão abaixo.) -- Esteja familiar com o gerenciamento de jobs no Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. +- Se familiarize com o gerenciamento de jobs em Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. - Aprenda `ssh`, e o básico de autenticação sem senha, através do `ssh-agent`, `ssh-add`, etc. -- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna significa no `ls -l` significa), `less`, `head`, `tail` e `tail -f` (ou ainda melhor, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links versos hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Gerenciamento básico de arquivos: `ls` e `ls -l` (em particular, aprenda o que cada coluna no `ls -l` significa), `less`, `head`, `tail` e `tail -f` (ou melhor ainda, `less +F`), `ln` e `ln -s`(aprenda as diferenças e vantagens de soft links comparados a hard links), `chown`, `chmod`, `du` (para um rápido resumo do uso do disco: `du -sk *`). Para gerenciamento do sistema de arquivos, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. - Gerenciamento básico da rede: `ip` ou `ifconfig`, `dig`. -- Sabia bem expressões regulares, e as várias flags para `grep`/`egrep`. As `-i`, `-o`, `-A`, e `-B` são opções que é importante saber. +- Saiba bem como usar expressões regulares, e as várias flags para `grep`/`egrep`. As `-i`, `-o`, `-A`, e `-B` são opções que é importante conhecer. -- Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas abaixo são fáceis de instalar através do `pip`). +- Aprenda a usar `apt-get`, `yum`, `dnf` ou `pacman` (dependendo da distribuição) para procurar e instalar pacotes. E garanta que você possui o `pip` para instalar ferramentas baseadas em Python (algumas das abaixo são mais fáceis de instalar através do `pip`). ## Uso diário -- No Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através do histórico de comandos. +- Usando Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através a história dos comandos. - No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. -- Como alternativa, se você ama os keybinds ao estilo do vi, use `set -o vi`. +- Alternativamente, se você adora os keybinds do vi, use `set -o vi`. - Para ver os comandos recentes, `history`. Existem também muitas abreviações como `!$` (último argumento) e `!!` último comando, embora estes sejam muitas vezes facilmente substituídos por **ctrl-r** e **alt-.**. -- Volte atrás para o diretório de trabalho anterior: `cd -`. +- Pra voltar para o diretório anterior de trabalho: `cd -`. -- Se você está na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início e defina este como um comentário (ou use **ctrl-a**. **#**. **enter**). Mais tarde você poderá recuperar o comando através do `history`. +- Se você está na metade do caminho ao digitar um comando, mas mudou de ideia, tecle **alt-#** para adicionar um `#` ao início da linha e definir esta como um comentário (ou use **ctrl-a**. **#**. **enter**). Mais tarde você poderá recuperar o comando através da `history`. - Use `xargs` (ou `parallel`). Estes são muito poderosos. Note que você pode controlar como os vários items são executados por linha (`-L`) assim como o paralelismo (`-P`). Se você não tem certeza se isto é a coisa certa a se fazer, use `xargs echo` primeiro. O `-I{}` também é muito útil. Exemplos: ```bash @@ -92,7 +91,7 @@ Notas: - Use `nohup` ou `disown` se você deseja por o processo em background executando para sempre. -- Verifique quais processos estão escutando através `netstat -lntp` ou `ss -plat` (para TCP; adicione `-u` para UDP). +- Verifique quais processos estão escutando através de `netstat -lntp` ou `ss -plat` (para TCP; adicione `-u` para UDP). - Veja também `lsof` para abrir sockets e arquivos. @@ -317,7 +316,7 @@ Alguns exemplos de como reunir os comandos. - `printenv`: imprime as variáveis de ambiente (útil em debug e scripts). -- `look`: procura palavras Inglesas (ou linhas em um arquivo) começando com uma string. +- `look`: procura palavras inglesas (ou linhas em um arquivo) começando com uma string. - `cut ` e `paste` e `join`: manipulação de dados. @@ -389,7 +388,7 @@ Alguns exemplos de como reunir os comandos. - `mtr`: melhor traceroute para debugar a rede. -- `cssh`: Visualização concorrente do shell. +- `cssh`: Visualização concorrente da shell. - `rsync`: Sincroniza arquivos e pastas através do SSH. @@ -403,7 +402,7 @@ Alguns exemplos de como reunir os comandos. - `dstat`: Estatísticas úteis do sistema. -- [`glances`](https://github.com/nicolargo/glances): Resumo em alto nível, de multi subsistemas. +- [`glances`](https://github.com/nicolargo/glances): Resumo de alto nível, de multi subsistemas. - `iostat`: Estatísticas de uso do CPU e do disco. @@ -435,16 +434,16 @@ Alguns exemplos de como reunir os comandos. ## Mais conteúdo -- [awesome-shell](https://github.com/alebcay/awesome-shell): Uma lista refinada de ferramentas do shell e outros recursos. +- [awesome-shell](https://github.com/alebcay/awesome-shell): Uma lista refinada de ferramentas da shell e outros recursos. - [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escrever shell scripts melhores. ## Aviso -Com a exceção de tarefas muito pequenas, o código é escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo no Bash não necessariamente significa que você deve! ;) +Com a exceção de tarefas muito pequenas, código é escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo usando Bash não significa necessariamente que você deve! ;) ## Licença [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -Este trabalho está licenciado sobre uma [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). +Este trabalho está licenciado com uma [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From 33794df7eb6fa661a9f6d3a54e58b6e59efc96d7 Mon Sep 17 00:00:00 2001 From: Valeria de Paiva Date: Sun, 28 Jun 2015 20:42:40 -0700 Subject: [PATCH 49/69] Update README-pt.md --- README-pt.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README-pt.md b/README-pt.md index 43b46f2..f0b0687 100644 --- a/README-pt.md +++ b/README-pt.md @@ -40,11 +40,11 @@ Notas: ## Básico -- Aprenda o básico sobre Bash. Na verdade, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativas podem ser legais, mas Bash é a mais poderosa e sempre está disponível (aprender *somente* zsh, fish, etc, é tentador quando voce usa o seu próprio laptop, mas restringe você em muitas situações, por exemplo quando você quer usar servidores de outros). +- Aprenda o básico sobre Bash. Na verdade, digite `man bash` e pelo menos entenda superficialmente o seu funcionamento; é bastante simples de ler e nem é tão grande assim. Shells alternativas podem ser legais, mas Bash é a mais poderosa e sempre está disponível (aprender *somente* zsh, fish, etc, é tentador quando você usa o seu próprio notebook, mas restringe você em muitas situações, por exemplo quando você quer usar servidores de outros). -- Aprenda bem pelo menos um editor de text tradicional. Idealmente o Vim (`vi`), já que nenhum outro funciona tão bem nos terminais aleatorios que a gente encontra por ai (mesmo que você prefira usar o Emacs, um IDE, ou um editor hipster a maior parte do tempo). +- Aprenda bem pelo menos um editor de text tradicional. Idealmente o Vim (`vi`), já que nenhum outro funciona tão bem nos terminais aleatórios que a gente encontra por ai (mesmo que você prefira usar o Emacs, um IDE, ou um editor hipster a maior parte do tempo). -- Saiba como ler a documentação com o `man` (para os curiosos, `man man` lista os números das seções, por exemplo, 1 se refere aos comandos "regulares", 5 é sobre arquivos/convenções, e 8 se diz respeito a administração). Procure outros documentos do manual com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, pra esses você poderá conseguir ajuda com `help` e `help -d`. +- Saiba como ler a documentação com o `man` (para os curiosos, `man man` lista os números das seções, por exemplo, 1 se refere aos comandos "regulares", 5 é sobre arquivos/convenções, e 8 diz respeito a administração). Procure outros documentos do manual com o `apropos`. Saiba que alguns dos comandos não são executáveis, mas sim built-ins(embutidos) no bash, pra esses você poderá conseguir ajuda com `help` e `help -d`. - Aprenda como fazer redirecionamento de saída e entrada usando `>` e `<` e pipes usando `|`. Aprenda sobre o stdout e stdin. @@ -67,7 +67,7 @@ Notas: - Usando Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através a história dos comandos. -- No Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. +- Em Bash, utilize **ctrl-w** para deletar a última palavra, e **ctrl-u** para deletar tudo e voltar para o início da linha. Use **alt-b** e **alt-f** para se mover por palavras, **ctrl-k** para apagar até o final da linha, **ctrl-l** para limpar a tela. Consulte `man readline` para todos os keybindings padrões do Bash. Existem muitos. Por exemplo **alt-.** circula através dos argumentos anteriores, e **alt-*** expande um glob. - Alternativamente, se você adora os keybinds do vi, use `set -o vi`. @@ -89,7 +89,7 @@ Notas: - Saiba os vários sinais que você pode enviar para um processo. Por exemplo, para suspender um processo, use `kill -STOP [pid]`. Para saber a lista completas dos sinais, veja `man 7 signal`. -- Use `nohup` ou `disown` se você deseja por o processo em background executando para sempre. +- Use `nohup` ou `disown` se você deseja por o processo no background, executando para sempre. - Verifique quais processos estão escutando através de `netstat -lntp` ou `ss -plat` (para TCP; adicione `-u` para UDP). @@ -97,7 +97,7 @@ Notas: - Em scripts Bash, use `set -x` para debugar a saída. Utilize modos estritos sempre que for possível. Use `set -e` para abortar em caso de erros. Use `set -o pipefail` para também ser restrito a respeito dos erros (embora este tópico seja um pouco sútil). Para scripts mais desenvolvidos, use também `trap`. -- Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente mover para um diretório de trabalho diferente, e.g. +- Em Bash scripts, subshells (escrito com parênteses) são formas convenientes de agrupar comandos. Um exemplo comum é temporariamente se mover para um diretório de trabalho diferente, e.g. ```bash # faz algo no diretório corrente (cd /some/other/dir && other-command) @@ -132,9 +132,9 @@ Notas: ControlPersist yes ``` -- Algumas outras opções relevantes para o ssh são sensíveis a segurança e deveriam ser habilitadas com cuidado, por exemplo para subrede ou host ou em redes confiáveis: `StrictHostKeyChecking=no`, `ForwardAgent=yes` +- Algumas outras opções relevantes para o ssh tem problemas de segurança e devem ser habilitadas com muito cuidado, por exemplo somente para subrede ou host ou em redes confiaveis (de confiança): `StrictHostKeyChecking=no`, `ForwardAgent=yes` -- Para conseguir as permissões em arquivo em forma octal, o qual é útil para as configurações do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: +- Para conseguir as permissões em arquivo em forma octal, o que é útil para a configuraçao do sistema mas não disponível no `ls` e fácil de se confundir, use algo como: ```sh stat -c '%A %a %n' /etc/timezone ``` @@ -173,7 +173,7 @@ Notas: - Aprenda a respeito do `tee` para copiar da entrada padrão (stdin) para um arquivo e também para a saída padrão (stdout), como no `ls -al | tee file.txt`. -- Aprenda que as configurações de localização afetam várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o US English. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n podem fazer o `sort` ou outros comandos executarem *muitas vezes* mais lentos. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente ignorar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. +- Aprenda que as configurações de localização afetam várias ferramentas da linha de comando em formas sutis, incluindo a ordem da ordenação e performance. A maioria das instalações do Linux irá definir `LANG` ou outras variáveis de localização para o ingles dos USA. Mas esteja ciente de que a ordem da ordenação irá mudar, caso você altere a localização. E saiba que as rotinas do i18n podem fazer o `sort` ou outros comandos executarem *muitas vezes* mais devagar. Em algumas situações (como o conjunto de operações ou as operações únicas abaixo) você pode seguramente eliminar a lentidão das rotinas do i18n inteiramente e usar a ordem baseada nos bytes, usando `export LC_ALL=C`. - Aprenda o básico sobre `awk` e `sed` para obtenção de informações simples de dados. Por exemplo, somar todos os números na terceira coluna de um arquivo de texto: `awk '{ x += $3 } END { print x }'`. Isto é provavelmente 3X mais rápido e 3X mais curto do que o equivalente em Python. @@ -226,7 +226,7 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Para saber o status da memória, execute e entenda a saída do `free` `vmstat`. Em particular, esteja ciente de que o valor "cached", é mantido pelo kernel Linux como um arquivo de cache, então este efetivamente conta como um valor de memória disponível. -- Debugar um sistema java é uma "kettle of fish", mas um simples truque nas máquinas virtuais Oracle ou algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo da heap (incluindo detalhes geracionais do garbage collector, os quais podem ser altamente informativos) serão vazados para stderr/logs. +- Debugar um sistema java é uma outra historia, mas um simples truque nas máquinas virtuais Oracle ou algum outro tipo de JVM é que você pode executar `kill -3 ` e um completo rastreamento da pilha(stack trace) e resumo do heap (incluindo detalhes geracionais do garbage collector, os quais podem ser altamente informativos) serão vazados para stderr/logs. - Use `mtr` como uma melhor alternativa ao traceroute, para identificar problemas na rede. @@ -244,22 +244,22 @@ Use `zsless`, `zmore`, `zcat`, and `zgrep` para manipular arquivos comprimidos. - Aprenda sobre como se conectar a um processo em execução com o `gdb` e obter informações sobre a stack trace. -- Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas vivos. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. +- Utilize `/proc`. Este é incrivelmente útil em algumas vezes quando se deseja debugar problemas ao vivo. Exemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. -- Quando estiver debugando o porque de algo ter dado errado no passado, `sar` pode ser de muita utilidade. Este exibe as estatísticas históricas da CPU, memória, rede e etc. +- Quando estiver debugando o porque de algo ter dado errado no passado, `sar` pode ser de muita utilidade. Ele exibe as estatísticas históricas da CPU, memória, rede e etc. - Para análises de performance mais profundas do sistema, dê uma olhada em `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), e [`sysdig`](https://github.com/draios/sysdig). - Confirme qual a sua distribuição do Linux usando (funciona na maioria das distros): `lsb_release -a`. -- Use `dmesg` sempre que algo estiver agindo de maneira estranha (isto poderia ser um hardware ou problemas de driver). +- Use `dmesg` sempre que algo estiver agindo de maneira estranha (isto pode ser um problema de hardware ou problema de driver). ## One-liners Alguns exemplos de como reunir os comandos. -- É notavelmente útil algumas vezes, que você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são únicos. Desse modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Ordenação não é limitada por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` a cima e as opções `-u` do `sort`(vamos deixar isso claro abaixo). +- O seguinte é notavelmente e frequentemente útil: muitas vezes você quer obter a interseção, união e a diferença de arquivos de texto através de `sort`/`uniq`. Suponha que `a` e `b` são arquivos de texto que são "uniqued" únicos. Esse modo é rápido, e funciona em arquivos de tamanhos arbitrários, podem até possuírem gigabytes. (Sorting não é limitado por memória, embora você possa precisar usar a opção `-T` se `/tmp` está em uma partição pequena.) Veja também a nota sobre `LC_ALL` acima e as opções `-u` do `sort`(vamos deixar isso claro abaixo). ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b @@ -274,7 +274,7 @@ Alguns exemplos de como reunir os comandos. awk '{ x += $3 } END { print x }' myfile ``` -- Se você quer visualizar tamanhos/datas em uma árvore de arquivos, isto é como uma `ls -l` recursivo, mas é mais fácil de ler do que `ls -lR`: +- Se você quer visualizar tamanhos/datas em uma árvore de arquivos, isto é como um `ls -l` recursivo, mas é mais fácil de ler do que `ls -lR`: ```sh find . -type f -ls ``` @@ -439,7 +439,7 @@ Alguns exemplos de como reunir os comandos. ## Aviso -Com a exceção de tarefas muito pequenas, código é escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo usando Bash não significa necessariamente que você deve! ;) +Com a exceção de tarefas muito pequenas, código é normalmente escrito para que outros possam ler. Junto com o poder vem a responsabilidade. O fato de você *poder* fazer algo usando Bash não significa necessariamente que você deve! ;) ## Licença From 299d3928fa952aaf3ff160f8445eb0170367f339 Mon Sep 17 00:00:00 2001 From: Chujie Zeng Date: Tue, 30 Jun 2015 02:41:57 +0800 Subject: [PATCH 50/69] Update README-zh.md --- README-zh.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/README-zh.md b/README-zh.md index 4563a7e..30c9356 100644 --- a/README-zh.md +++ b/README-zh.md @@ -3,6 +3,7 @@ # 命令行的艺术 +[![Join the chat at https://gitter.im/jlevy/the-art-of-command-line](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jlevy/the-art-of-command-line?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - [必读](#必读) - [基础](#基础) - [日常使用](#日常使用) @@ -56,7 +57,7 @@ - 了解 `ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add` 等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解 `ls -l` 中每一列代表的意义),`less`,`head`,`tail` 和 `tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -sk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 +- 学会基本的文件管理: `ls` 和 `ls -l` (了解 `ls -l` 中每一列代表的意义),`less`,`head`,`tail` 和 `tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -hk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 - 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 @@ -194,9 +195,7 @@ - 使用 `shuf` 从一个文件中随机选取行。 -- 了解 `sort` 的参数。明白键的工作原理(`-t` 和 `-k`)。例如,注意到你需要 `-k1,1` 来仅按第一个域来排序,而 `-k1` 意味着按整行排序。 - -- 稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用 `sort -k1,1 | sort -s -k2,2` +- 了解 `sort` 的参数。明白键的工作原理(`-t` 和 `-k`)。例如,注意到你需要 `-k1,1` 来仅按第一个域来排序,而 `-k1` 意味着按整行排序。稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用 `sort -k1,1 | sort -s -k2,2`。处理可读性数字(例如 `du -h` 的输出)的时候使用 `sort -h` 。 - 如果你想在 Bash 命令行中写 tab 制表符,按下 **ctrl-v** **[Tab]** 或键入 `$'\t'` (后者可能更好,因为你可以复制粘贴它)。 @@ -429,7 +428,7 @@ - `lsblk`: 列出块设备信息: 以树形展示你的磁盘以及磁盘分区信息 -- `lshw` 及 `lspci`: 查看硬件信息,包括 RAID、显卡等 +- `lshw`,`lscpu`,`lspci`,`lsusb` 和 `dmidecode`: 查看硬件信息,包括 CPU、BIOS、RAID、显卡、USB设备等 - `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" @@ -447,6 +446,6 @@ ## 授权条款 -[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) +[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -本文使用授权协议 [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/)。 +本文使用授权协议 [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/)。 From 099248530f804acb53ca177cd7e952a9645b151d Mon Sep 17 00:00:00 2001 From: taxusyew Date: Tue, 30 Jun 2015 10:50:19 +0800 Subject: [PATCH 51/69] just one word --- README-zh.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-zh.md b/README-zh.md index 30c9356..398293a 100644 --- a/README-zh.md +++ b/README-zh.md @@ -219,7 +219,7 @@ ## 系统调试 -- `curl` 和 `curl -I` 可以便捷地被应用于 web 调试中,它们的好兄弟 `wget` 也可以,或者是更潮流的 [`httpie`](https://github.com/jakubroztocil/httpie)。 +- `curl` 和 `curl -I` 可以便捷地被应用于 web 调试中,它们的好兄弟 `wget` 也可以,或者是更潮的 [`httpie`](https://github.com/jakubroztocil/httpie)。 - 使用 `iostat`、`netstat`、`top` (`htop` 更佳)和 `dstat` 去获取硬盘、cpu 和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 From 389273adb20e9d7a815561a00812681c71a6b9fc Mon Sep 17 00:00:00 2001 From: Chunyang Xu Date: Tue, 30 Jun 2015 10:59:44 +0800 Subject: [PATCH 52/69] zh: Fix typos This commit includes one typo fix reported in #140 by @zhyueh fix #140 --- README-zh.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-zh.md b/README-zh.md index 30c9356..6c96321 100644 --- a/README-zh.md +++ b/README-zh.md @@ -251,7 +251,7 @@ - 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 -- 查看你当前使用的 Linux 发型版(大部分发行版有效): `lsb_release -a` +- 查看你当前使用的 Linux 发行版(大部分发行版有效): `lsb_release -a` - 无论什么东西工作得很欢乐时试试 `dmesg` (可能是硬件或驱动问题)。 @@ -269,7 +269,7 @@ - 使用 `grep . *` 来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如 `/sys`、`/proc`、`/etc`。 -- 计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码块三倍且代码量少三倍): +- 计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码快三倍且代码量少三倍): ```sh awk '{ x += $3 } END { print x }' myfile ``` From cab1b9fae1063ce15857b830221034130379cc0a Mon Sep 17 00:00:00 2001 From: Chujie Zeng Date: Wed, 1 Jul 2015 00:37:23 +0800 Subject: [PATCH 53/69] Full-width punctuation marks Replace half-width punctuation mark with full-width punctuation mark in Chinese --- README-zh.md | 250 +++++++++++++++++++++++++-------------------------- 1 file changed, 125 insertions(+), 125 deletions(-) diff --git a/README-zh.md b/README-zh.md index ddf79a3..230c6b6 100644 --- a/README-zh.md +++ b/README-zh.md @@ -23,47 +23,47 @@ 这里的大部分内容 [首次](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) [出现](http://www.quora.com/What-are-the-most-useful-Swiss-army-knife-one-liners-on-Unix) -于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用 Github 来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交 Issue 或 Pull Request!(当然在提交前请看一下必读节和已有的 PR/issue)。 +于 [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know),但考虑到这里的人们都具有学习的天赋且乐于接受别人的建议,使用 Github 来做这件事是更佳的选择。如果你在本文中发现了错误或者存在可以改善的地方,请果断提交 Issue 或 Pull Request!(当然在提交前请看一下必读节和已有的 PR/issue)。 ## 必读 -涵盖范围: +涵盖范围: -- 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为 Linux 所写,但很多内容(并非所有的)同样适用于 MacOS 甚至 Cygwin。 +- 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 +- 本文为 Linux 所写,但很多内容(并非所有的)同样适用于 MacOS 甚至 Cygwin。 - 本文关注于交互式 Bash,尽管很多技巧适用于其他 shell 或 Bash 脚本。 -- 本文包括了"标准的"Unix 命令和需要安装特定包的命令,只要它们足够重要。 +- 本文包括了“标准的”Unix 命令和需要安装特定包的命令,只要它们足够重要。 -注意事项: +注意事项: -- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`(以及其它合适的包管理器)来安装新程序。 +- 为了能在一页内展示尽量多的东西,一些具体的信息会被间接的包含在引用页里。聪明机智的你如果掌握了使用 Google 搜索引擎的基本思路与命令,那么你将可以查阅到更多的详细信息。使用 `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew`(以及其它合适的包管理器)来安装新程序。 - 使用 [Explainshell](http://explainshell.com/) 去获取相关命令、参数、管道等内容的解释。 ## 基础 -- 学习 Bash 的基础知识。具体来说,输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的 shell 可能很好用,但 Bash 功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh,fish 或其他的 shell 的话,在你自己的电脑上会显得很方便,但在很多情况下会限制你,比如当你需要在服务器上工作时)。 +- 学习 Bash 的基础知识。具体来说,输入 `man bash` 并至少全文浏览一遍; 它很简单并且不长。其他的 shell 可能很好用,但 Bash 功能强大且几乎所有情况下都是可用的 ( *只*学习 zsh,fish 或其他的 shell 的话,在你自己的电脑上会显得很方便,但在很多情况下会限制你,比如当你需要在服务器上工作时)。 -- 学习并掌握至少一个基于文本的编辑器。通常 Vim (`vi`) 会是你最好的选择。 +- 学习并掌握至少一个基于文本的编辑器。通常 Vim (`vi`) 会是你最好的选择。 - 学会如何使用 `man` 命令去阅读文档。学会使用 `apropos` 去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用 `help` 和 `help -d` 命令获取帮助信息。 - 学会使用 `>` 和 `<` 来重定向输出和输入,学会使用 `|` 来重定向管道。了解标准输出 stdout 和标准错误 stderr。 -- 学会使用通配符 `*` (或许再算上 `?` 和 `{`...`}`) 和引用以及引用中 `'` 和 `"` 的区别。 +- 学会使用通配符 `*` (或许再算上 `?` 和 `{`...`}`) 和引用以及引用中 `'` 和 `"` 的区别。 -- 熟悉 Bash 任务管理工具: `&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 +- 熟悉 Bash 任务管理工具:`&`,**ctrl-z**,**ctrl-c**,`jobs`,`fg`,`bg`,`kill` 等。 - 了解 `ssh`,以及基本的无密码认证,`ssh-agent`,`ssh-add` 等。 -- 学会基本的文件管理: `ls` 和 `ls -l` (了解 `ls -l` 中每一列代表的意义),`less`,`head`,`tail` 和 `tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述: `du -hk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 +- 学会基本的文件管理:`ls` 和 `ls -l` (了解 `ls -l` 中每一列代表的意义),`less`,`head`,`tail` 和 `tail -f` (甚至 `less +F`),`ln` 和 `ln -s` (了解硬链接与软链接的区别),`chown`,`chmod`,`du` (硬盘使用情况概述:`du -hk *`)。 关于文件系统的管理,学习 `df`,`mount`,`fdisk`,`mkfs`,`lsblk`。 -- 学习基本的网络管理: `ip` 或 `ifconfig`,`dig`。 +- 学习基本的网络管理:`ip` 或 `ifconfig`,`dig`。 -- 熟悉正则表达式,以及 `grep`/`egrep` 里不同参数的作用,例如 `-i`,`-o`,`-A`,和 `-B`。 +- 熟悉正则表达式,以及 `grep`/`egrep` 里不同参数的作用,例如 `-i`,`-o`,`-A`,和 `-B`。 -- 学会使用 `apt-get`,`yum`,`dnf` 或 `pacman` (取决于你使用的 Linux 发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于 Python 的命令行工具 (部分程序使用 `pip` 来安装会很简单)。 +- 学会使用 `apt-get`,`yum`,`dnf` 或 `pacman` (取决于你使用的 Linux 发行版)来查找或安装包。确保你的环境中有 `pip` 来安装基于 Python 的命令行工具 (部分程序使用 `pip` 来安装会很简单)。 ## 日常使用 @@ -74,13 +74,13 @@ - 你喜欢的话,可以键入 `set -o vi` 来使用 vi 风格的快捷键。 -- 键入 `history` 查看命令行历史记录。其中有许多缩写,例如 `!$`(最后键入的参数)和 `!!`(最后键入的命令),尽管通常被 **ctrl-r** 和 **alt-.** 取代。 +- 键入 `history` 查看命令行历史记录。其中有许多缩写,例如 `!$`(最后键入的参数)和 `!!`(最后键入的命令),尽管通常被 **ctrl-r** 和 **alt-.** 取代。 -- 回到上一个工作路径: `cd -` +- 回到上一个工作路径:`cd -` -- 如果你输入命令的时候改变了主意,按下 **alt-#** 在行首添加 `#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 +- 如果你输入命令的时候改变了主意,按下 **alt-#** 在行首添加 `#`(将你输入的命令视为注释),并回车。这样做的话,之后你可以很方便的利用命令行历史回到你刚才输入到一半的命令。 -- 使用 `xargs` ( 或 `parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: +- 使用 `xargs` ( 或 `parallel`)。他们非常给力。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname @@ -94,35 +94,35 @@ - 使用 `nohup` 或 `disown` 使一个后台进程持续运行。 -- 使用 `netstat -lntp` 或 `ss -plat` 检查哪些进程在监听端口(默认是检查 TCP 端口; 使用参数 `-u` 检查 UDP 端口)。 +- 使用 `netstat -lntp` 或 `ss -plat` 检查哪些进程在监听端口(默认是检查 TCP 端口; 使用参数 `-u` 检查 UDP 端口)。 - 有关打开套接字和文件,请参阅 `lsof`。 -- 在 Bash 脚本中,使用 `set -x` 去调试输出,尽可能的使用严格模式,使用 `set -e` 令脚本在发生错误时退出而不是继续运行,使用 `set -o pipefail` 严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用 `trap`。 +- 在 Bash 脚本中,使用 `set -x` 去调试输出,尽可能的使用严格模式,使用 `set -e` 令脚本在发生错误时退出而不是继续运行,使用 `set -o pipefail` 严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用 `trap`。 -- 在 Bash 脚本中,子 shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: +- 在 Bash 脚本中,子 shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: ```bash # do something in current dir (cd /some/other/dir && other-command) # continue in original dir ``` -- 在 Bash 中,注意到其中有许多形式的扩展。检查变量是否存在: `${name:?error message}`。例如,当 Bash 脚本需要一个参数时,可以使用这样的代码 `input_file=${1:?usage: $0 input_file}`。数学表达式: `i=$(( (i + 1) % 5 ))`。序列: `{1..10}`。 截断字符串: `${var%suffix}` 和 `${var#prefix}`。例如,假设 `var=foo.pdf`,那么 `echo ${var%.pdf}.txt` 将输出 `foo.txt`。 +- 在 Bash 中,注意到其中有许多形式的扩展。检查变量是否存在:`${name:?error message}`。例如,当 Bash 脚本需要一个参数时,可以使用这样的代码 `input_file=${1:?usage: $0 input_file}`。数学表达式:`i=$(( (i + 1) % 5 ))`。序列:`{1..10}`。 截断字符串:`${var%suffix}` 和 `${var#prefix}`。例如,假设 `var=foo.pdf`,那么 `echo ${var%.pdf}.txt` 将输出 `foo.txt`。 -- 通过使用 `<(some command)` 可以将输出视为文件。例如,对比本地文件 `/etc/hosts` 和一个远程文件: +- 通过使用 `<(some command)` 可以将输出视为文件。例如,对比本地文件 `/etc/hosts` 和一个远程文件: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- 了解 Bash 中的"here documents",例如 `cat <logfile 2>&1`。通常,为了保证命令不会在标准输入里残留一个打开了的文件句柄导致你当前所在的终端无法操作,添加 `; ::Any-NFC; ' < input.txt > output.txt ``` -- 拆分文件,查看 `split`(按大小拆分)和 `csplit`(按模式拆分)。 +- 拆分文件,查看 `split`(按大小拆分)和 `csplit`(按模式拆分)。 - 使用 `zless`,`zmore`,`zcat` 和 `zgrep`对压缩过的文件进行操作。 @@ -221,13 +221,13 @@ - `curl` 和 `curl -I` 可以便捷地被应用于 web 调试中,它们的好兄弟 `wget` 也可以,或者是更潮的 [`httpie`](https://github.com/jakubroztocil/httpie)。 -- 使用 `iostat`、`netstat`、`top` (`htop` 更佳)和 `dstat` 去获取硬盘、cpu 和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 +- 使用 `iostat`、`netstat`、`top` (`htop` 更佳)和 `dstat` 去获取硬盘、cpu 和网络的状态。熟练掌握这些工具可以使你快速的对系统的当前状态有一个大概的认识。 - 若要对系统有一个深度的总体认识,使用 [`glances`](https://github.com/nicolargo/glances)。它在一个终端窗口中向你提供一些系统级的数据。这对于快速的检查各个子系统非常有帮助。 -- 若要了解内存状态,运行并理解 `free` 和 `vmstat` 的输出。尤其注意"cached"的值,它指的是 Linux 内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 +- 若要了解内存状态,运行并理解 `free` 和 `vmstat` 的输出。尤其注意“cached”的值,它指的是 Linux 内核用来作为文件缓存的内存大小,因此它与空闲内存无关。 -- Java 系统调试则是一件截然不同的事,一个可以用于 Oracle 的 JVM 或其他 JVM 上的调试的小技巧是你可以运行 `kill -3 ` 同时一个完整的栈轨迹和堆概述(包括 GC 的细节)会被保存到标准输出/日志文件。 +- Java 系统调试则是一件截然不同的事,一个可以用于 Oracle 的 JVM 或其他 JVM 上的调试的小技巧是你可以运行 `kill -3 ` 同时一个完整的栈轨迹和堆概述(包括 GC 的细节)会被保存到标准输出/日志文件。 - 使用 `mtr` 去跟踪路由,用于确定网络问题。 @@ -235,32 +235,32 @@ - 查找正在使用带宽的套接字连接或进程,使用 `iftop` 或 `nethogs`。 -- `ab` 工具(捆绑于 Apache)可以简单粗暴地检查 web 服务器的性能。对于更复杂的负载测试,使用 `siege`。 +- `ab` 工具(捆绑于 Apache)可以简单粗暴地检查 web 服务器的性能。对于更复杂的负载测试,使用 `siege`。 - `wireshark`,`tshark` 和 `ngrep` 可用于复杂的网络调试。 -- 了解 `strace` 和 `ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意 profile 参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 +- 了解 `strace` 和 `ltrace`。这俩工具在你的程序运行失败、挂起甚至崩溃,而你却不知道为什么或你想对性能有个总体的认识的时候是非常有用的。注意 profile 参数(`-c`)和附加到一个运行的进程参数 (`-p`)。 - 了解使用 `ldd` 来检查共享库。 - 了解如何运用 `gdb` 连接到一个运行着的进程并获取它的堆栈轨迹。 -- 学会使用 `/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如: `/proc/cpuinfo`,`/proc/xxx/cwd`,`/proc/xxx/exe`,`/proc/xxx/fd/`,`/proc/xxx/smaps`。 +- 学会使用 `/proc`。它在调试正在出现的问题的时候有时会效果惊人。比如:`/proc/cpuinfo`,`/proc/xxx/cwd`,`/proc/xxx/exe`,`/proc/xxx/fd/`,`/proc/xxx/smaps`。 - 当调试一些之前出现的问题的时候,`sar` 非常有用。它展示了 cpu、内存以及网络等的历史数据。 -- 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 +- 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 -- 查看你当前使用的 Linux 发行版(大部分发行版有效): `lsb_release -a` +- 查看你当前使用的 Linux 发行版(大部分发行版有效):`lsb_release -a` -- 无论什么东西工作得很欢乐时试试 `dmesg` (可能是硬件或驱动问题)。 +- 无论什么东西工作得很欢乐时试试 `dmesg` (可能是硬件或驱动问题)。 ## 一行代码 -一些命令组合的例子: +一些命令组合的例子: -- 当你需要对文本文件做集合交、并、差运算时,结合使用 `sort`/`uniq` 很有帮助。假设 `a` 与 `b` 是两内容不同的文件。这种方式效率很高,并且在小文件和上G的文件上都能运用 (`sort` 不被内存大小约束,尽管在 `/tmp` 在一个小的根分区上时你可能需要 `-T` 参数),参阅前文中关于 `LC_ALL` 和 `sort` 的 `-u` 参数的部分。 +- 当你需要对文本文件做集合交、并、差运算时,结合使用 `sort`/`uniq` 很有帮助。假设 `a` 与 `b` 是两内容不同的文件。这种方式效率很高,并且在小文件和上G的文件上都能运用 (`sort` 不被内存大小约束,尽管在 `/tmp` 在一个小的根分区上时你可能需要 `-T` 参数),参阅前文中关于 `LC_ALL` 和 `sort` 的 `-u` 参数的部分。 ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b @@ -269,28 +269,28 @@ - 使用 `grep . *` 来阅读检查目录下所有文件的内容,例如检查一个充满配置文件的目录比如 `/sys`、`/proc`、`/etc`。 -- 计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码快三倍且代码量少三倍): +- 计算文本文件第三列中所有数的和(可能比同等作用的 Python 代码快三倍且代码量少三倍): ```sh awk '{ x += $3 } END { print x }' myfile ``` -- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的 `ls -l` 但比 `ls -lR` 更易于理解: +- 如果你想在文件树上查看大小\日期,这可能看起来像递归版的 `ls -l` 但比 `ls -lR` 更易于理解: ```sh find . -type f -ls ``` -- 尽可能的使用 `xargs` 或 `parallel`。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: +- 尽可能的使用 `xargs` 或 `parallel`。注意到你可以控制每行参数个数(`-L`)和最大并行数(`-P`)。如果你不确定它们是否会按你想的那样工作,先使用 `xargs echo` 查看一下。此外,使用 `-I{}` 会很方便。例如: ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- 假设你有一个类似于 web 服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个 `acct_id` 参数在URI中。如果你想计算出每个 `acct_id` 值有多少次请求,使用如下代码: +- 假设你有一个类似于 web 服务器日志文件的文本文件,并且一个确定的值只会出现在某些行上,假设一个 `acct_id` 参数在URI中。如果你想计算出每个 `acct_id` 值有多少次请求,使用如下代码: ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- 运行这个函数从这篇文档中随机获取一条小技巧(解析 Markdown 文件并抽取项目): +- 运行这个函数从这篇文档中随机获取一条小技巧(解析 Markdown 文件并抽取项目): ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | @@ -304,138 +304,138 @@ ## 冷门但有用 -- `expr`: 计算表达式或正则匹配 +- `expr`:计算表达式或正则匹配 -- `m4`: 简单地宏处理器 +- `m4`:简单地宏处理器 -- `yes`: 多次打印字符串 +- `yes`:多次打印字符串 -- `cal`: 漂亮的日历 +- `cal`:漂亮的日历 -- `env`: 执行一个命令(脚本文件中很有用) +- `env`:执行一个命令(脚本文件中很有用) -- `printenv`: 打印环境变量(调试时或在使用脚本文件时很有用) +- `printenv`:打印环境变量(调试时或在使用脚本文件时很有用) -- `look`: 查找以特定字符串开头的单词 +- `look`:查找以特定字符串开头的单词 -- `cut`、`paste` 和 `join`: 数据修改 +- `cut`、`paste` 和 `join`:数据修改 -- `fmt`: 格式化文本段落 +- `fmt`:格式化文本段落 -- `pr`: 将文本格式化成页/列形式 +- `pr`:将文本格式化成页/列形式 -- `fold`: 包裹文本中的几行 +- `fold`:包裹文本中的几行 -- `column`: 将文本格式化成多列或表格 +- `column`:将文本格式化成多列或表格 -- `expand` 和 `unexpand`: 制表符与空格之间转换 +- `expand` 和 `unexpand`:制表符与空格之间转换 -- `nl`: 添加行号 +- `nl`:添加行号 -- `seq`: 打印数字 +- `seq`:打印数字 -- `bc`: 计算器 +- `bc`:计算器 -- `factor`: 分解因数 +- `factor`:分解因数 -- `gpg`: 加密并签名文件 +- `gpg`:加密并签名文件 -- `toe`: terminfo entries 列表 +- `toe`:terminfo entries 列表 -- `nc`: 网络调试及数据传输 +- `nc`:网络调试及数据传输 -- `socat`: 套接字代理,与 `netcat` 类似 +- `socat`:套接字代理,与 `netcat` 类似 -- `slurm`: 网络可视化 +- `slurm`:网络可视化 -- `dd`: 文件或设备间传输数据 +- `dd`:文件或设备间传输数据 -- `file`: 确定文件类型 +- `file`:确定文件类型 -- `tree`: 以树的形式显示路径和文件,类似于递归的 `ls` +- `tree`:以树的形式显示路径和文件,类似于递归的 `ls` -- `stat`: 文件信息 +- `stat`:文件信息 -- `tac`: 反向输出文件 +- `tac`:反向输出文件 -- `shuf`: 文件中随机选取几行 +- `shuf`:文件中随机选取几行 -- `comm`: 一行一行的比较排序过的文件 +- `comm`:一行一行的比较排序过的文件 -- `pv`: 监视通过管道的数据 +- `pv`:监视通过管道的数据 -- `hd` 和 `bvi`: 保存或编辑二进制文件 +- `hd` 和 `bvi`:保存或编辑二进制文件 -- `strings`: 从二进制文件中抽取文本 +- `strings`:从二进制文件中抽取文本 -- `tr`: 转换字母 +- `tr`:转换字母 -- `iconv` 或 `uconv`: 简易的文件编码 +- `iconv` 或 `uconv`:简易的文件编码 -- `split` 和 `csplit`: 分割文件 +- `split` 和 `csplit`:分割文件 -- `units`: 将一种计量单位转换为另一种等效的计量单位(参阅 `/usr/share/units/definitions.units`) +- `units`:将一种计量单位转换为另一种等效的计量单位(参阅 `/usr/share/units/definitions.units`) -- `7z`: 高比例的文件压缩 +- `7z`:高比例的文件压缩 -- `ldd`: 动态库信息 +- `ldd`:动态库信息 -- `nm`: 提取 obj 文件中的符号 +- `nm`:提取 obj 文件中的符号 -- `ab`: 性能分析 web 服务器 +- `ab`:性能分析 web 服务器 -- `strace`: 系统调用调试 +- `strace`:系统调用调试 -- `mtr`: 更好的网络调试跟踪工具 +- `mtr`:更好的网络调试跟踪工具 -- `cssh`: 可视化的并发 shell +- `cssh`:可视化的并发 shell -- `rsync`: 通过 ssh 同步文件和文件夹 +- `rsync`:通过 ssh 同步文件和文件夹 -- `wireshark` 和 `tshark`: 抓包和网络调试工具 +- `wireshark` 和 `tshark`:抓包和网络调试工具 -- `ngrep`: 网络层的 grep +- `ngrep`:网络层的 grep -- `host` 和 `dig`: DNS 查找 +- `host` 和 `dig`:DNS 查找 -- `lsof`: 列出当前系统打开文件的工具以及查看端口信息 +- `lsof`:列出当前系统打开文件的工具以及查看端口信息 -- `dstat`: 系统状态查看 +- `dstat`:系统状态查看 -- [`glances`](https://github.com/nicolargo/glances): 高层次的多子系统总览 +- [`glances`](https://github.com/nicolargo/glances):高层次的多子系统总览 -- `iostat`: CPU 和硬盘状态 +- `iostat`:CPU 和硬盘状态 -- `htop`: top 的加强版 +- `htop`:top 的加强版 -- `last`: 登入记录 +- `last`:登入记录 -- `w`: 查看处于登录状态的用户 +- `w`:查看处于登录状态的用户 -- `id`: 用户/组 ID 信息 +- `id`:用户/组 ID 信息 -- `sar`: 系统历史数据 +- `sar`:系统历史数据 -- `iftop` 或 `nethogs`: 套接字及进程的网络利用 +- `iftop` 或 `nethogs`:套接字及进程的网络利用 -- `ss`: 套接字数据 +- `ss`:套接字数据 -- `dmesg`: 引导及系统错误信息 +- `dmesg`:引导及系统错误信息 -- `hdparm`: SATA/ATA 磁盘更改及性能分析 +- `hdparm`:SATA/ATA 磁盘更改及性能分析 -- `lsb_release`: Linux 发行版信息 +- `lsb_release`:Linux 发行版信息 -- `lsblk`: 列出块设备信息: 以树形展示你的磁盘以及磁盘分区信息 +- `lsblk`:列出块设备信息:以树形展示你的磁盘以及磁盘分区信息 -- `lshw`,`lscpu`,`lspci`,`lsusb` 和 `dmidecode`: 查看硬件信息,包括 CPU、BIOS、RAID、显卡、USB设备等 +- `lshw`,`lscpu`,`lspci`,`lsusb` 和 `dmidecode`:查看硬件信息,包括 CPU、BIOS、RAID、显卡、USB设备等 -- `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否"有用" +- `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否“有用” ## 更多资源 -- [awesome-shell](https://github.com/alebcay/awesome-shell): 一份精心组织的命令行工具及资源的列表。 +- [awesome-shell](https://github.com/alebcay/awesome-shell): 一份精心组织的命令行工具及资源的列表。 - [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/): 为了编写更好的脚本文件。 From ebb065b66795c1686c267fa4f674a41796e935be Mon Sep 17 00:00:00 2001 From: Chujie Zeng Date: Wed, 1 Jul 2015 00:39:57 +0800 Subject: [PATCH 54/69] Fix error --- README-zh.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-zh.md b/README-zh.md index 230c6b6..0e7d6ba 100644 --- a/README-zh.md +++ b/README-zh.md @@ -144,7 +144,7 @@ - 使用 [`percol`](https://github.com/mooz/percol) 可以交互式地从另一个命令输出中选取值。 -- 使用 `fpp`([PathPicker](https://github.com/facebook/PathPicker))可以与基于另一个命令(例如 `git`)输出的文件交互。 +- 使用 `fpp`([PathPicker](https://github.com/facebook/PathPicker))可以与基于另一个命令(例如 `git`)输出的文件交互。 - 将 web 服务器上当前目录下所有的文件(以及子目录)暴露给你所处网络的所有用户,使用: `python -m SimpleHTTPServer 7777` (使用端口 7777 和 Python 2)或`python -m http.server 7777` (使用端口 7777 和 Python 3)。 @@ -249,7 +249,7 @@ - 当调试一些之前出现的问题的时候,`sar` 非常有用。它展示了 cpu、内存以及网络等的历史数据。 -- 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 +- 关于更深层次的系统分析以及性能分析,看看 `stap`([SystemTap](https://sourceware.org/systemtap/wiki)),[`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)),以及[`sysdig`](https://github.com/draios/sysdig)。 - 查看你当前使用的 Linux 发行版(大部分发行版有效):`lsb_release -a` From 6c26b698623f903917ff615a0f1ce66000b2ab0b Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Wed, 1 Jul 2015 21:58:16 -0700 Subject: [PATCH 55/69] Correct omission of sort -n. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec29e3c..7a61169 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ Notes: - Use `shuf` to shuffle or select random lines from a file. -- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `sort -k1,1 | sort -s -k2,2`. For handling human-readable numbers (e.g. from `du -h`) use `sort -h`. +- Know `sort`'s options. For numbers, use `-n`, or `-h` for handling human-readable numbers (e.g. from `du -h`). Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means 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 use `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). From d05219e092b44878f253468b7f18bfc8a7960cc3 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 3 Jul 2015 00:26:37 +0300 Subject: [PATCH 56/69] WIP: section Everyday use --- README-es.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README-es.md b/README-es.md index 4ece35b..5bee53e 100644 --- a/README-es.md +++ b/README-es.md @@ -64,29 +64,29 @@ Notas: - Aprenda el uso de `apt-get`, `yum`, `dnf` o `pacman` (dependiendo de la dismtribución "distro") para buscar e instalar paquetes. Y asegurate que tienes `pip` para instalar la herramienta de linea de comando basada en Python (un poco más abajo esta super fácil para instalar vía `pip`). -## Everyday use +## De uso diario -- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. +- En Bash, se usa **Tab** para completar los argumentos y **ctrl-r** para buscar, a través, del historial de comandos. -- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete all the way back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob. +- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar to delete todo el camino hasta el inicio de la línea. Se usa **alt-b** y **alt-f** para moverse entre letras, **ctrl-k** para eliminar hasta el final de la línea, **ctrl-l** para limpiar la panatalla. Ver `man readline` para todos los atajos de teclado por defecto en Bash. Son una gran cantidad. Por ejemplo **alt-.** cicla, a través, de los comandos previos, y **alt-*** expande un glob. -- Alternatively, if you love vi-style key-bindings, use `set -o vi`. +- Alternativamente, si tu amas los atajos de teclado vi-style, usa `set -o vi`. -- To see recent commands, `history`. There are also many abbreviations such as `!$` (last argument) and `!!` last command, though these are often easily replaced with **ctrl-r** and **alt-.**. +- Para ver los últimos comandos, `history`. También existen abreviaciones, tales como, `!$` (último argumento) y `!!` último comando, auque sin facílmente remplazados con **ctrl-r** y **alt-.**. -- To go back to the previous working directory: `cd -` +- Para volver al diretorio de trabajo previo: `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. +- Si estas a mitad de camino de escritura de un comando pero cambias de opinión, presiona **alt-#** para agregar un `#` al princio y lo agrega como comantario (o usar **ctrl-a**, **#**, **enter**). Para que puedas entonces regresar a este luego vía comando historyYou can then return to it later via command history. -- Use `xargs` (or `parallel`). 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, use `xargs echo` first. Also, `-I{}` is handy. Examples: +- `Se usa `xargs` (or `parallel`). Este es muy poderoso. Nota: tú puedes controlar muchos items por ejecutados por línea (`-L`) tamabién, es conocido como paralelismo (`-P`). Si no estas seguro, esto puede ser la cosa correcta, usa `xargs echo` primero. También, `-I{}` es comodo. Ejemplos: ```bash find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- `pstree -p` is a helpful display of the process tree. +- `pstree -p` es útil para mostrar el árbol de procesos. -- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). +- Se usa `pgrep` y `pkill` para encontrar o señalar procesos por su nombre (`-f` es de mucha ayuda). - Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` From cba6daafda73a43d53738e2ca0a75d9467b7c499 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 00:22:55 -0700 Subject: [PATCH 57/69] Include uname Fixes #114. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a61169..5ddfa10 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ Notes: - For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). -- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` +- Check what OS you're on with `uname` or `uname -a` (general Unix/kernel info) or `lsb_release -a` (Linux distro info). - Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). From 27eb7509a121dbd8a0ee99a9d67ba042c53621a8 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 00:46:48 -0700 Subject: [PATCH 58/69] New section specific to MacOS. Fixes #153, #134. --- README.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5ddfa10..d5178e4 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ - [System debugging](#system-debugging) - [One-liners](#one-liners) - [Obscure but useful](#obscure-but-useful) +- [MacOS only](#macos-only) - [More resources](#more-resources) - [Disclaimer](#disclaimer) @@ -32,7 +33,7 @@ but given the interest there, it seems it's worth using Github, where people mor Scope: - This guide is both for beginners and the experienced. 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. Many but not all items apply equally to MacOS (or even Cygwin). +- This is written for Linux, with the exception of the "[MacOS only](#macos-only)" section. Many of the other items apply or can be installed on other Unices or MacOS (or even Cygwin). - The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting. - 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. @@ -435,6 +436,21 @@ A few examples of piecing together commands: - `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" +## MacOS only + +These are items relevant *only* on MacOS. + +- Package management with `brew` (Homebrew) and/or `port` (MacPorts). These can be used to install on MacOS many of the above commands. + +- Copy output of any command with `pbcopy` and paste input with `pbpaste`. + +- To open a file with a desktop app, use `open` or `open -a /Applications/Whatever.app`. + +- Spotlight: Search files with `mdfind` and list metadata (such as photo EXIF info) with `mdls`. + +- 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 as `gawk` and `gsed` for GNU awk and sed). + + ## More resources - [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. From f4789f0aa4d0c1494e7ef79276b71bf2c6b8d21b Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 00:52:01 -0700 Subject: [PATCH 59/69] One more update to MacOS section. #153 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d5178e4..65b2189 100644 --- a/README.md +++ b/README.md @@ -442,13 +442,13 @@ These are items relevant *only* on MacOS. - Package management with `brew` (Homebrew) and/or `port` (MacPorts). These can be used to install on MacOS many of the above commands. -- Copy output of any command with `pbcopy` and paste input with `pbpaste`. +- Copy output of any command to a desktop app with `pbcopy` and paste input from one with `pbpaste`. - To open a file with a desktop app, use `open` or `open -a /Applications/Whatever.app`. - Spotlight: Search files with `mdfind` and list metadata (such as photo EXIF info) with `mdls`. -- 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 as `gawk` and `gsed` for GNU awk and sed). +- 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 as `gawk` and `gsed` for GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully. ## More resources From d623fee2e09e8343a29c4fc6734492bac87ee9a8 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 00:54:30 -0700 Subject: [PATCH 60/69] Mention appending with >>. Fixes #151. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 65b2189..a5d9b89 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Notes: - Know how to read documentation with `man` (for the inquisitive, `man man` lists the section numbers, e.g. 1 is "regular" commands, 5 is files/conventions, and 8 are for administration). Find man pages with `apropos`. Know that some commands are not executables, but Bash builtins, and that you can get help on them with `help` and `help -d`. -- Learn about redirection of output and input using `>` and `<` and pipes using `|`. Learn about stdout and stderr. +- Learn about redirection of output and input using `>` and `<` and pipes using `|`. Know `>` overwrites the output file and `>>` appends. Learn about stdout and 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.) From 2a68e1aab59e8c46bde8ea56571b25597005f4fd Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 00:59:32 -0700 Subject: [PATCH 61/69] Add sudo and su. Fixes #150. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a5d9b89..db5b175 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,8 @@ Notes: - 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) and `python -m http.server 7777` (for port 7777 and Python 3). +- For running a command with privileges, use `sudo` (for root) or `sudo -u` (for another user). Use `su` or `sudo bash` to actually run a shell as that user. Use `su -` to simulate a fresh login as root or another user. + ## Processing files and data From 1262a25e9a989eb1c48b84aad93cf86409e8b546 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 01:13:06 -0700 Subject: [PATCH 62/69] Add sponge #60 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index db5b175..6f82761 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,8 @@ A few examples of piecing together commands: - `split `and `csplit`: splitting files +- `sponge`: read all input to memory before wriring it, useful for reading from then writing to the same file (for example, `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`) - `7z`: high-ratio file compression From d285213f08cb732997af5014a228bbad296a26e0 Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 01:15:18 -0700 Subject: [PATCH 63/69] Fix language re sponge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6f82761..ea6b753 100644 --- a/README.md +++ b/README.md @@ -379,7 +379,7 @@ A few examples of piecing together commands: - `split `and `csplit`: splitting files -- `sponge`: read all input to memory before wriring it, useful for reading from then writing to the same file (for example, `grep -v something some-file | sponge some-file`) +- `sponge`: read all input before wriring it, useful for reading from then writing to the same file, e.g., `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`) From b09a1864e38b3515ff97f58b7603395d83fc059c Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 01:19:26 -0700 Subject: [PATCH 64/69] Add fzf Fixes #96 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ea6b753..d6775ed 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ Notes: stat -c '%A %a %n' /etc/timezone ``` -- For interactive selection of values from the output of another command, use [`percol`](https://github.com/mooz/percol). +- For interactive selection of values from the output of another command, use [`percol`](https://github.com/mooz/percol) or [`fzf`](https://github.com/junegunn/fzf). - For interaction with files based on the output of another command (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). From 7469c72e0f0b50ddf42946fd704cdee856262a2d Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 02:14:04 -0700 Subject: [PATCH 65/69] Move alias info to "Everyday use." Better fit in that section. #119 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 38ca118..870a2f3 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,6 @@ Notes: - 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.) -- Use `alias` to create shortcuts or synonyms for commonly used commands. For example: `alias ll='ls -latr'` creates a new alias `ll`. - - Be familiar with Bash job management: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. - Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc. @@ -102,6 +100,8 @@ Notes: - See also `lsof` for open sockets and files. +- Use `alias` to create shortcuts for commonly used commands. For example, `alias ll='ls -latr'` creates a new alias `ll`. + - In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. - 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. From 5d55f360d2da226d99f42196448cba61ae235e2c Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 3 Jul 2015 12:45:47 +0300 Subject: [PATCH 66/69] docs: De uso diario --- README-es.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/README-es.md b/README-es.md index 5bee53e..168c83c 100644 --- a/README-es.md +++ b/README-es.md @@ -88,41 +88,41 @@ Notas: - Se usa `pgrep` y `pkill` para encontrar o señalar procesos por su nombre (`-f` es de mucha ayuda). -- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` +- Conocer varias señales que puedes enviar a los procesos. Por ejemplo, para suspender un proceso, usa `kill -STOP [pid]`. Para la lista completa, consultar `man 7 signal` -- Use `nohup` or `disown` if you want a background process to keep running forever. +- Usa `nohup` o `disown` si quieres mantener un proceso de fondo corriendo para siempre. -- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). +- Verifica que procesos esta escuchando via `netstat -lntp` o `ss -plat` (para TCP; agrega `-u` para UDP). -- See also `lsof` for open sockets and files. +- Consulta también `lsof` para abrir sockets y archivos. -- In Bash scripts, use `set -x` for debugging output. Use strict modes whenever possible. Use `set -e` to abort on errors. Use `set -o pipefail` as well, to be strict about errors (though this topic is a bit subtle). For more involved scripts, also use `trap`. +- En Bash scripts, usa `set -x` para depurar la salida. Utiliza el modo estricto cuando se posible. Utiliza `set -e` para abortar en errores. Utiliza `set -o pipefail` también, para ser estrictos sobre los errores (auque este tema es un poco delicado). Para scripts más complejos, también se puede utilizar `trap`. -- 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. +- En Bash scripts, subshells (escritos con parentesís) son maneras convenientes para agrupar los comandos. Un ejemplo común es para moverse temporalment hacia un diferente directorio de trabajo, Ej. ```bash # 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 write `input_file=${1:?usage: $0 input_file}`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`. +- En Bash, considere que hay muchas formas de expansión de vaiables. Verificar la existencia de una variable: `${name:?error message}`. Por ejemplo, si un script Bash requiere un único argumento, solo escriba `input_file=${1:?usage: $0 input_file}`. Expansión arítmetica: `i=$(( (i + 1) % 5 ))`. Secuencias: `{1..10}`. Reducción de strings: `${var%suffix}` y `${var#prefix}`. Por ejemplo si `var=foo.pdf`, entonces `echo ${var%.pdf}.txt` imprime `foo.txt`. -- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +- La salida de un comando puede ser tratado como un archivo, via `<(some command)`. Por ejemplo, compare local `/etc/hosts` con uno remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- Know about "here documents" in Bash, as in `cat <logfile 2>&1`. 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 `logfile 2>&1`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estandar, vinculado al terminal en el que te encuentras, esta también como buena practica puedes agregar ` Date: Fri, 3 Jul 2015 14:13:53 +0300 Subject: [PATCH 67/69] WIP: Procesamiento de archivos y data --- README-es.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README-es.md b/README-es.md index 168c83c..3fb1d07 100644 --- a/README-es.md +++ b/README-es.md @@ -148,33 +148,33 @@ Notas: `python -m SimpleHTTPServer 7777` (para el puerto 7777 y Python 2) y `python -m http.server 7777` (para 7777 y Python 3). -## Processing files and data +## Procesamiento de archivos y datos -- To locate a file by name in the current directory, `find . -iname '*something*'` (or similar). To find a file anywhere by name, use `locate something` (but bear in mind `updatedb` may not have indexed recently created files). +- Para localizar un archivo por nombre en el directorio actual, `find . -iname '*something*'` (o similar). Para encontrar un archivo en cualquier lado por nombre, usar `locate something` (pero tenga en mente `updatedb` quizas no haya indexado recientement los archivos creados). -- For general searching through source or data files (more advanced than `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). +- Por lo general buscar por la fuente o archivos de datos (más avanzado que `grep -r`), usar [`ag`](https://github.com/ggreer/the_silver_searcher). -- To convert HTML to text: `lynx -dump -stdin` +- Para convertir HTML a text: `lynx -dump -stdin` -- For Markdown, HTML, and all kinds of document conversion, try [`pandoc`](http://pandoc.org/). +- Para Markdown, HTML, y todos los tipos de conversión de documentos, probar [`pandoc`](http://pandoc.org/). -- If you must handle XML, `xmlstarlet` is old but good. +- Si debes manipular XML, `xmlstarlet` es viejo pero bueno. -- For JSON, use `jq`. +- Para JSON, usa `jq`. -- For Excel or CSV files, [csvkit](https://github.com/onyxfish/csvkit) provides `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. +- Para archivos Excel o CSV, [csvkit](https://github.com/onyxfish/csvkit) provee `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. -- For Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) is convenient and [`s4cmd`](https://github.com/bloomreach/s4cmd) is faster. Amazon's [`aws`](https://github.com/aws/aws-cli) is essential for other AWS-related tasks. +- Para Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) es conveniente y [`s4cmd`](https://github.com/bloomreach/s4cmd) es el mas rápido. Hecho por Amazon [`aws`](https://github.com/aws/aws-cli) es esencial para otras tareas relacionadas al AWS. -- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. +- Conocer acerca `sort` y `uniq`, incluyendo opciones de uniq `-u` y `-d` -- ver unas lineas mas abajo. -- Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`. +- Conocer acerca `cut`, `paste`, y `join` para manipular archivos de texto. Muchas personas usan `cut` pero se olvidan acerca de `join`. -- Know about `wc` to count newlines (`-l`), characters (`-m`), words (`-w`) and bytes (`-c`). +- Conocer acerca `wc` para contar nuevas líneas (`-l`), caractéres (`-m`), palabras (`-w`) y bytes (`-c`). -- Know about `tee` to copy from stdin to a file and also to stdout, as in `ls -al | tee file.txt`. +- Conocer acerca `tee` para copiar desde el stdin hacia un archivo y también hacia el stdout, así `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 `LANG` or 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, using `export LC_ALL=C`. +- Conocer que locale afecta muchas herramientas de línea de comando en forma delicada, incluyendo el orden del ordenamiento (compaginación) y rendimeinto. La mayoria de las instalaciones de Linux configuran `LANG` u otras variables de localización para la configuración local como US English. Pero este alerta, el ordenamiento puede cambiar su cambia la localización. Y también las rutinas i18n pueden hacer que sort u otros comandos se ejecuten *muchas mas veces* mas lentos. En algunas situaciones (tales como la realización de operaciones u operaciones singulares debajo) puede de forma segura ignorar las turinas lentas i18n por completo y utilizar el sort tradcional basado en byte, usando `export LC_ALL=C`. - Know basic `awk` and `sed` for simple data munging. For example, summing all numbers in the third column of a text file: `awk '{ x += $3 } END { print x }'`. This is probably 3X faster and 3X shorter than equivalent Python. From 605d75fb09a967fc4d2eb391c9d6494fb29a7101 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 3 Jul 2015 19:45:43 +0300 Subject: [PATCH 68/69] dos: the rest. --- README-es.md | 224 +++++++++++++++++++++++++-------------------------- 1 file changed, 112 insertions(+), 112 deletions(-) diff --git a/README-es.md b/README-es.md index 3fb1d07..71e22eb 100644 --- a/README-es.md +++ b/README-es.md @@ -176,14 +176,14 @@ Notas: - Conocer que locale afecta muchas herramientas de línea de comando en forma delicada, incluyendo el orden del ordenamiento (compaginación) y rendimeinto. La mayoria de las instalaciones de Linux configuran `LANG` u otras variables de localización para la configuración local como US English. Pero este alerta, el ordenamiento puede cambiar su cambia la localización. Y también las rutinas i18n pueden hacer que sort u otros comandos se ejecuten *muchas mas veces* mas lentos. En algunas situaciones (tales como la realización de operaciones u operaciones singulares debajo) puede de forma segura ignorar las turinas lentas i18n por completo y utilizar el sort tradcional basado en byte, usando `export LC_ALL=C`. -- Know basic `awk` and `sed` for simple data munging. For example, summing all numbers in the third column of a text file: `awk '{ x += $3 } END { print x }'`. This is probably 3X faster and 3X shorter than equivalent Python. +- Conozca esencial `awk` y `sed` para mapeo de datos sencillo. Por ejemplo, sumar todos lo números en la tercera columna de un archivo de texto: `awk '{ x += $3 } END { print x }'`. Esto es probablemente 3X más rápido y 3X más corto que su equivalente en Python. -- To replace all occurrences of a string in place, in one or more files: +- Para remplanzar todas las ocurrencias de un string en su lugar, en uno o más archivos: ```sh perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt ``` -- To rename many files at once according to a pattern, use `rename`. For complex renames, [`repren`](https://github.com/jlevy/repren) may help. +- Para renombrar varios archivos a la vez de acuerdo a un patron, usar `rename`. Para renombramientos complejos, [`repren`](https://github.com/jlevy/repren) may help. ```sh # Recover backup files foo.bak -> foo: rename 's/\.bak$//' *.bak @@ -191,107 +191,107 @@ Notas: repren --full --preserve-case --from foo --to bar . ``` -- Use `shuf` to shuffle or select random lines from a file. +- Usar `shuf` para mezclar o seleccionar líneas aleatoreas desde un archivo. -- Know `sort`'s options. Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means sort according to the whole line. +- Conozca las opciones de `sort`. Conozca el trabajo principal de (`-t` y `-k`). En particular, este atento que lo necesitara para escribir`-k1,1` para ordenar por solo el primer campo; `-k1` significa ordenar de acuerdo a toda la línea. -- Stable sort (`sort -s`) can be useful. For example, to sort first by field 2, then secondarily by field 1, you can use `sort -k1,1 | sort -s -k2,2` +- Orden estable (`sort -s`) puede ser útil. Por ejemplo, para organizar el primer por el campo 2, entonces secundariamente de hacerlo por el campo 1, Puedes usar `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). +- Si tu siempre necesitas escribir un tab literal en una línea de comandos en Bash (Ej. para el argumento -t de ordenar), presione **ctrl-v** **[Tab]** o escriba `$'\t'` (El último es mejor porque puedes copiarlo/pegarlo). -- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. +- Las herramientas estandar para reparar el código fuente son `diff` y `patch`. Ver también `diffstat` para resumen estadístico de una diff. Nota `diff -r` trabaja con directorios por completo. Usar`diff -r tree1 tree2 | diffstat` para el resumen de cambios. -- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. +- Para archivos binarios, usar `hd` para sencillos "hex dumps" y `bvi` para edición de binario. -- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. +- También para archivos binarios, `strings` (además de `grep`, etc.) permite encontrar en el texto bits. -- For binary diffs (delta compression), use `xdelta3`. +- Para diffs binaria (delta compression), usar `xdelta3`. -- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example, this command lowercases and removes all accents (by expanding and dropping them): +- Para convertir To convert la codificación del texto, probar `iconv`. O `uconv` para el uso avanzado; este soporta este soporta algunos elementos Unicode avanzados. Por ejemplo, este coloca en minúsculas y remueve todos los acentos (por expanción y colocandolos a ellos): ```sh 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) and `csplit` (to split by a pattern). +- Para dividir archivos en multiples partes, consultar `split` (para dividir por tamaño) y `csplit` (para dividir por un patrón). -- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files. +- Usar `zless`, `zmore`, `zcat`, y `zgrep` para operar sobre archivos comprimidos. -## System debugging +## Depuración del sistema -- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jakubroztocil/httpie). +- Para depuración web, `curl` y `curl -I` son prácticos, o sus equivalentes `wget`, o el más moderno [`httpie`](https://github.com/jakubroztocil/httpie). -- To know disk/cpu/network status, use `iostat`, `netstat`, `top` (or the better `htop`), and (especially) `dstat`. Good for getting a quick idea of what's happening on a system. +- Para el estado del disco/cpu/red, usar `iostat`, `netstat`, `top` (o el mejor `htop`), y (especialmente) `dstat`. Bueno para recibir una idea rápida de lo que esta pasando en tu sistema. -- For a more in-depth system overview, use [`glances`](https://github.com/nicolargo/glances). It presents you with several system level statistics in one terminal window. Very helpful for quickly checking on various subsystems. +- Para una resumen en mayor profundidad, usar [`glances`](https://github.com/nicolargo/glances). Este se presenta con varios niveles de estadística en un solo terminal. Muy útil para una verificación rápida de vaios subsistemas. -- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value. +- Para conocer el estado de la memoria, ejecutar y entender la salida de `free` y `vmstat`. En particular, tener en cuenta el valor "cached" es memoria mantenida por el kernel Linux como un archivo de cache, entonces efectivamente cuenta como valor para "free". -- 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 ` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. +- El sistema de deputación de Java es harina de otro costal, pero un truco simple en las JSM de Oracle y de otros consta en que puedes ejecutar `kill -3 ` y una traza completa y un resumen del montículo "heap summary" (incluyendo del detalle de la collección de basura generacional, la cual puede ser altamente informativa) seran descargados al stderr/logs. -- Use `mtr` as a better traceroute, to identify network issues. +- Usar `mtr` como un mejor traceroute, para identificar los problemas en la red. -- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. +- Para mirara porque el disco esta lleno, `ncdu` ahorra tiempo sobre los comandos usual como `du -sh *`. -- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. +- Para encontrar cual socket o proceso esta utilizando el ancho de banda, prueba `iftop` o `nethogs`. -- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`. +- La herramienta `ab` (viene con Apache) es útil para una verificación rapida y sucia del rendimiento del servidor web. Para pruebas de carga más complejas, prueba `siege`. -- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. +- Para depuración de redes más serias, `wireshark`, `tshark`, o `ngrep`. -- Know about `strace` and `ltrace`. 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`). +- Conozca acerca `strace` y `ltrace`. Estas son de utilidad si un programa esta fallando, guindando, o estrellando, y no conoces por qué?, o si quieres tener una idea general del rendimiento. Note la opción de elaboración de perfiles (`-c`), y la habilidad de adjuntar a un proceso en ejecución (`-p`). -- Know about `ldd` to check shared libraries etc. +- Conozca acerca `ldd` para verificar librerias compartidas etc. -- Know how to connect to a running process with `gdb` and get its stack traces. +- Conozca como conectarse a un proceso en ejecución con `gdb` y obtener su traza de pilas. -- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. +- Usar `/proc`. Este es extraordinariamente útil algunas veces cuando hay problemas de deputación en vivo. Ejemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. -- When debugging why something went wrong in the past, `sar` can be very helpful. It shows historic statistics on CPU, memory, network, etc. +- Cuando se depura porque algo salio más en el pasado, `sar` puede ser muy útil. Este muestra la estadistica historica en CPU, memoria, red, etc. -- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), and [`sysdig`](https://github.com/draios/sysdig). +- Para sistemas y analisís de rendimiento de mayor profundidad, ver `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), y [`sysdig`](https://github.com/draios/sysdig). -- Confirm what Linux distribution you're using (works on most distros): `lsb_release -a` +- Confirmar que distribución de Linux estas utilizando (trabaja en a mayoría de los distros): `lsb_release -a` -- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). +- Usar `dmesg` siempre que algo actue comico (esto podría ser problemas con el hardware o driver). ## One-liners -A few examples of piecing together commands: +Algunos ejemplos de comandos reunidos: -- It is remarkably helpful sometimes that you can do set intersection, union, and difference of text files via `sort`/`uniq`. Suppose `a` and `b` are 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 `-T` option if `/tmp` is on a small root partition.) See also the note about `LC_ALL` above and `sort`'s `-u` option (left out for clarity below). +- Este es remarcablemente útil en ocasiones que hay que realizar intersección, unión, y diferencia de archivos de texto via `sort`/`uniq`. Considere `a` y `b` son archivos de texto que son ya unicos. Esto es rápido, y trabaja con archivos de tamaño arbitrario, hasta varios gigabytes. (Sort no esta limitado por la memoria, aunque quizas necesites utilizar la opción `-T` si `/tmp` esta en una pequeña partición raíz.) Ver también la nota acerca `LC_ALL` y las opciones de `sort`, `-u` (dejado de lado para clarificar mas abajo). ```sh cat a b | sort | uniq > c # c is a union b cat a b | sort | uniq -d > c # c is a intersect b cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- Use `grep . *` to visually examine all contents of all files in a directory, e.g. for directories filled with config settings, like `/sys`, `/proc`, `/etc`. +- Usar `grep . *` para visualmente examinar todo el contenido de todos los archivos de un directorio, Ej. para directorios llenos con parametros de configuración, como `/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): +- Sumar todos os números en la tercera columna de un archivo de texto (esto es probablemente 3X más rapido 3X menor código que el equivalente en Python): ```sh awk '{ x += $3 } END { print x }' myfile ``` -- If want to see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`: +- Si quiere ver tamaños/fechas en un árbol de archivos, esto es como hacer recursivo `ls -l` pero es mas facil de leer que `ls -lR`: ```sh find . -type f -ls ``` -- Use `xargs` or `parallel` whenever you can. 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, use xargs echo first. Also, `-I{}` is handy. Examples: +- Usar `xargs` o `parallel` cuando pueda. Considere que puede controlar algunos elementos ejecutados por línea (`-L`) así como paralelismo (`-P`). Si no esta seguro de estar haciendo la cosa correcta, use primero xargs echo. También, `-I{}` es práctico. Ejemplos: ```sh find . -name '*.py' | xargs grep some_function cat hosts | xargs -I{} ssh root@{} hostname ``` -- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`: +- Digamos que tiene un archivo de texto, como un log de un servidor web, y un cierto valor comienza a aparecer en algunas líneas, tales como un parametro `acct_id` que esta presente en el URL. Si quieres un recuento de cuantas peticiones ""request hay por cada `acct_id`: ```sh cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- Run this function to get a random tip from this document (parses Markdown and extracts an item): +- Ejecta esta función para obtener un consejo aleatoreo desde este documento (analiza el Markdown y extrae un elemento): ```sh function taocl() { curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md | @@ -303,148 +303,148 @@ A few examples of piecing together commands: ``` -## Obscure but useful +## Obscuro pero útil -- `expr`: perform arithmetic or boolean operations or evaluate regular expressions +- `expr`: ejecuta operaciones aritmeticas o booleanas o evalua expresiones regulares -- `m4`: simple macro processor +- `m4`: macro procesador sencillo -- `yes`: print a string a lot +- `yes`: imprime un string sin fin -- `cal`: nice calendar +- `cal`: lindo calendario -- `env`: run a command (useful in scripts) +- `env`: ejecuta un comando (útil en scripts) -- `printenv`: print out environment variables (useful in debugging and scripts) +- `printenv`: imprime las variables del ambiente (útil en depuración y scripts) -- `look`: find English words (or lines in a file) beginning with a string +- `look`: buscar palabras en English (o líneas en un archivo) comanzando con un string -- `cut `and `paste` and `join`: data manipulation +- `cut`, `paste` y `join`: manipulación de datos -- `fmt`: format text paragraphs +- `fmt`: formato de texto de parrafo -- `pr`: format text into pages/columns +- `pr`: formato de texto en páginas/columnas -- `fold`: wrap lines of text +- `fold`: envolturas de líneas de texto -- `column`: format text into columns or tables +- `column`: formato de texto en columnas o tablas -- `expand` and `unexpand`: convert between tabs and spaces +- `expand` y `unexpand`: convertidor entre tabs y espacios -- `nl`: add line numbers +- `nl`: agrega números de línea -- `seq`: print numbers +- `seq`: imprime números -- `bc`: calculator +- `bc`: calculadora -- `factor`: factor integers +- `factor`: factorización de enteros -- `gpg`: encrypt and sign files +- `gpg`: cifrado y firmas digitales -- `toe`: table of terminfo entries +- `toe`: tabla de información de terminos -- `nc`: network debugging and data transfer +- `nc`: deputación del entorno de red y transferencia de datos -- `socat`: socket relay and tcp port forwarder (similar to `netcat`) +- `socat`: socket relay y redireccionador de puerto tcp (similar a `netcat`) -- `slurm`: network trafic visualization +- `slurm`: visualización del tráfico de red -- `dd`: moving data between files or devices +- `dd`: moviliza data entre archivos y dispositivos -- `file`: identify type of a file +- `file`: identifica el typo de archivo -- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive +- `tree`: muestra directorios y subdirectorios como un árbol anidado; parecido a `ls` pero recursivo -- `stat`: file info +- `stat`: información del archivo -- `tac`: print files in reverse +- `tac`: imprime archivos en forma inversa -- `shuf`: random selection of lines from a file +- `shuf`: selección de líneas de un archivo de forma aleatorea -- `comm`: compare sorted files line by line +- `comm`: compara archivos ordenados línea por línea -- `hd` and `bvi`: dump or edit binary files +- `hd` y `bvi`: descarga o edita archivos binarios -- `strings`: extract text from binary files +- `strings`: extrae textos de archivos binarios -- `tr`: character translation or manipulation +- `tr`: traducción y manipulación de caracter -- `iconv` or `uconv`: conversion for text encodings +- `iconv` o `uconv`: conversión de codificaciones de texto -- `split `and `csplit`: splitting files +- `split` y `csplit`: división de archivos -- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) +- `units`: unidades de conversión y calculaciones; convierte furlongs por fortnight para twips por blink (ver también `/usr/share/units/definitions.units`) -- `7z`: high-ratio file compression +- `7z`: conpresión de archivos de alto nivel -- `ldd`: dynamic library info +- `ldd`: información de libreria dinamica -- `nm`: symbols from object files +- `nm`: archivo de objeto de simbolos -- `ab`: benchmarking web servers +- `ab`: benchmarking de servdores web -- `strace`: system call debugging +- `strace`: depuración de llamadas del sistema -- `mtr`: better traceroute for network debugging +- `mtr`: mejor traceroute para la deputación de la red -- `cssh`: visual concurrent shell +- `cssh`: shell concurrent visual -- `rsync`: sync files and folders over SSH +- `rsync`: sincronización de archivos y carpetas sobre SSH -- `wireshark` and `tshark`: packet capture and network debugging +- `wireshark` y `tshark`: captura de paquetes y depuración de la red -- `ngrep`: grep for the network layer +- `ngrep`: grep para la capa de la red -- `host` and `dig`: DNS lookups +- `host` y `dig`: consulta DNS -- `lsof`: process file descriptor and socket info +- `lsof`: descriptor de archivo de procesos y información de socket -- `dstat`: useful system stats +- `dstat`: sistema de estadisticas útil -- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview +- [`glances`](https://github.com/nicolargo/glances):vistazo de multi-subsistemas, de alto nivel -- `iostat`: CPU and disk usage stats +- `iostat`: estadísticas del CPU y uso del disco -- `htop`: improved version of top +- `htop`: version mejorada de top -- `last`: login history +- `last`: historial de login -- `w`: who's logged on +- `w`: quien esta authenticado? -- `id`: user/group identity info +- `id`: información de identidad de usuario/grupo -- `sar`: historic system stats +- `sar`: sistema de estadisticas historico -- `iftop` or `nethogs`: network utilization by socket or process +- `iftop` o `nethogs`: utilización de la red por un socket o process -- `ss`: socket statistics +- `ss`: estadisticas de socket -- `dmesg`: boot and system error messages +- `dmesg`: arranque y sistema de mensajes de error -- `hdparm`: SATA/ATA disk manipulation/performance +- `hdparm`: manipulación/rendimiento de discos SATA/ATA -- `lsb_release`: Linux distribution info +- `lsb_release`: información de la distribución de Linux -- `lsblk`: List block devices: a tree view of your disks and disk paritions +- `lsblk`: Lista de bloques de dispositivos: un árbol de vista de sus discos y particiones de disco -- `lshw`: hardware information +- `lshw`: información de hardware -- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful" +- `fortune`, `ddate`, y `sl`: um, bien, este depende si tiene la consideración de locomotoras de vapor y citas Zippy "práctico" -## More resources +## Más recursos -- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources. -- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts. +- [awesome-shell](https://github.com/alebcay/awesome-shell): Una lista curada de herramientas shell y recursos. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escribir mejores script shell. -## Disclaimer +## Advertencia -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! ;) +Con excepción de pequeñas tareas, el código está escrito para que otros puedan leerlo. Con el poder llega la responsabilidad. El hecho de que tú *puedes* hacer algo en Bash no necesaria mente significa que debas hacerlo! ;) -## License +## Licencia [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/) -This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/). +Este trabajo esta licenciado bajo [Creative Commons Attribution-ShareAlike 4.0 International Licene](http://creativecommons.org/licenses/by-sa/4.0/). From 217da3b4fa751014ecc122fd9fede2328a7eeb3e Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Fri, 3 Jul 2015 09:56:41 -0700 Subject: [PATCH 69/69] =?UTF-8?q?New=20language=20links=20(Espa=C3=B1ol).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-es.md | 3 ++- README-pt.md | 2 +- README-zh.md | 2 +- README.md | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README-es.md b/README-es.md index 71e22eb..3b43e14 100644 --- a/README-es.md +++ b/README-es.md @@ -1,4 +1,5 @@ -[ Languages: [中文](README-zh.md), [Español](README-es.md) ] +[ Languages: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] + # El Arte del Terminal diff --git a/README-pt.md b/README-pt.md index f0b0687..a85c14f 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] +[ Languages: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] # A arte da linha de comando diff --git a/README-zh.md b/README-zh.md index 0e7d6ba..41e4fb7 100644 --- a/README-zh.md +++ b/README-zh.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] +[ Languages: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] # 命令行的艺术 diff --git a/README.md b/README.md index 870a2f3..2b4a08b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ -[ Languages: [English](README.md), [Português](README-pt.md), [中文](README-zh.md) ] +[ Languages: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] + # The Art of Command Line