From aa20e47e0d03d48068fd22d99772315bccf11fbf Mon Sep 17 00:00:00 2001 From: kesu Date: Wed, 24 Jun 2015 15:28:50 +0000 Subject: [PATCH 01/43] 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 02/43] 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 a6f2e01e625acf362a8fb794a24d3f16805e4c34 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 26 Jun 2015 00:30:19 +0300 Subject: [PATCH 03/43] 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 ccc23ffb49c2cae3a44108a09e09679a38683bdb Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Sun, 28 Jun 2015 23:48:37 +0300 Subject: [PATCH 04/43] 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 6c26b698623f903917ff615a0f1ce66000b2ab0b Mon Sep 17 00:00:00 2001 From: Joshua Levy Date: Wed, 1 Jul 2015 21:58:16 -0700 Subject: [PATCH 05/43] 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 06/43] 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 07/43] 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 08/43] 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 09/43] 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 10/43] 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 11/43] 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 12/43] 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 13/43] 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 14/43] 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 15/43] 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 16/43] 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 17/43] 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 d42304acd3b7e38e2da92094f700eca7c49c2bf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matja=C5=BE=20Lipu=C5=A1?= Date: Fri, 3 Jul 2015 13:44:31 +0200 Subject: [PATCH 18/43] fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 870a2f3..f0c52c4 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,7 @@ A few examples of piecing together commands: - `split `and `csplit`: splitting files -- `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` +- `sponge`: read all input before writing it, useful for reading from then writing to the same file, e.g., `grep -v something some-file | sponge some-file` - `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) From 605d75fb09a967fc4d2eb391c9d6494fb29a7101 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 3 Jul 2015 19:45:43 +0300 Subject: [PATCH 19/43] 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 20/43] =?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 From 6fd486b4325be53d17615052223c15c652c54360 Mon Sep 17 00:00:00 2001 From: Carlos Mantilla Date: Fri, 3 Jul 2015 21:52:22 +0300 Subject: [PATCH 21/43] docs: actualizaciones --- README-es.md | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/README-es.md b/README-es.md index 71e22eb..3014e04 100644 --- a/README-es.md +++ b/README-es.md @@ -1,7 +1,9 @@ -[ 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 +[![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) - [Fundamentos](#basics) - [De uso diario](#everyday-use) @@ -9,6 +11,7 @@ - [Depuración del sistema](#system-debugging) - [One-liners](#one-liners) - [Obscuro pero útil](#obscure-but-useful) +- [Solo para MacOS](#macos-only) - [Más recursos](#more-resources) - [Advertencia](#disclaimer) @@ -29,7 +32,7 @@ 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. 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). +- Esta escrito para Linux, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros Unices o 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. @@ -47,7 +50,7 @@ Notas: - 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`. -- Aprenda sobre redirección de salida y entrada `>` y `<` and pipes utilizando `|`. Aprenda sobre stdout y stderr. +- Aprenda sobre redirección de salida y entrada `>` y `<` and pipes utilizando `|`. Conozca `>` sobre escribe el archivo de salida y `>>` añade. Aprenda sobre stdout y stderr. - 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.) @@ -55,7 +58,7 @@ Notas: - Conoce `ssh`, y lo básico de authenticacion sin password, via `ssh-agent`, `ssh-add`, etc. -- 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`. +- Adminisración de archivos básica: `ls` y `ls -l` (en particular, aprenda el significado de cada columna en `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 -hk *`). Para administración de filesystem, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. - Administración de redes básico: `ip` o `ifconfig`, `dig`. @@ -96,6 +99,8 @@ Notas: - Consulta también `lsof` para abrir sockets y archivos. +- Usar `alias` para crear atajos para comandos comúnmente usados. Por ejemplo, `alias ll="las -latr"` crea un nuevo alias `ll` + - 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`. - 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. @@ -118,7 +123,7 @@ Notas: - Usa `man ascii` para una buena tabla ASCII, con valores hexadecimal y decimales. Para información de codificación general, `man unicode`, `man utf-8`, y `man latin1` son de utilidad. -- Usa `screen` o `tmux` para multiplexar la pantalla, espcialmente útil en sessiones ss remotas y para desconectar y reconectar a una sessión. Una alternativa más minimalista para persistencia de la sessión solo sería `dtach`. +- Usa `screen` o [`tmux`](https://tmux.github.io/) para multiplexar la pantalla, espcialmente útil en sessiones ss remotas y para desconectar y reconectar a una sessión. Una alternativa más minimalista para persistencia de la sessión solo sería `dtach`. - En ssh, conocer como hacer un port tunnel con `-L` o `-D` (y de vez en cuando `-R`) es útil, Ej. para acceder sitio web desde un servidor remoto. @@ -140,13 +145,15 @@ Notas: stat -c '%A %a %n' /etc/timezone ``` -- Para selección interactiva de valores desde la salida de otro comando, usa [`percol`](https://github.com/mooz/percol). +- Para selección interactiva de valores desde la salida de otro comando, usa [`percol`](https://github.com/mooz/percol) o [`fzf`](https://github.com/junegunn/fzf). - Para la interacción con archivos basados en la salida de otro comando (como `git`), usa `fpp` ([PathPicker](https://github.com/facebook/PathPicker)). - Para un servidor web sencillo para todos los archivos en el directorio actual (y subdirectorios), disponible para cualquiera en tu red, usa: `python -m SimpleHTTPServer 7777` (para el puerto 7777 y Python 2) y `python -m http.server 7777` (para 7777 y Python 3). +- Para ejecutar un comando con privilagios, usando `sudo` (para root) o `sudo -u` (para otro usuario). Usar `su` o `sudo bash` para realmente ejecutar un shell como este usuario. Usar `su -` para simular un login fresco como root u otro usuario. + ## Procesamiento de archivos y datos @@ -193,9 +200,7 @@ Notas: - Usar `shuf` para mezclar o seleccionar líneas aleatoreas desde un archivo. -- 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. - -- 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` +- Conozca las opciones de `sort`. Para números, use `-n`, o `-h` para manipulación de números humanamente leibles (Ej. desde `du -h`). 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. Orden estable (`sort -s`) puede ser útil. Por ejemplo, para organizar el primer por el campo 2, entonces secundariamente hacerlo por el campo 1, Puedes usar `sort -k1,1 | sort -s -k2,2`. - 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). @@ -251,7 +256,7 @@ Notas: - 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). -- Confirmar que distribución de Linux estas utilizando (trabaja en a mayoría de los distros): `lsb_release -a` +- Confirmar que OS te encuentras con `uname` o `uname -a` (información general Unix/kernel) o `lsb_release -a` (Linux distro info). - Usar `dmesg` siempre que algo actue comico (esto podría ser problemas con el hardware o driver). @@ -363,6 +368,8 @@ Algunos ejemplos de comandos reunidos: - `comm`: compara archivos ordenados línea por línea +- `pv`: monitor del progreso de datos, a través, de un tubo + - `hd` y `bvi`: descarga o edita archivos binarios - `strings`: extrae textos de archivos binarios @@ -373,6 +380,8 @@ Algunos ejemplos de comandos reunidos: - `split` y `csplit`: división de archivos +- `sponge`: lee todas las entradas antes de escribirlo, útil para lectura desde useful for reading y luego la escritura hacia el mismo archivo, Ej., `grep -v something some-file | sponge some-file` + - `units`: unidades de conversión y calculaciones; convierte furlongs por fortnight para twips por blink (ver también `/usr/share/units/definitions.units`) - `7z`: conpresión de archivos de alto nivel @@ -427,11 +436,26 @@ Algunos ejemplos de comandos reunidos: - `lsblk`: Lista de bloques de dispositivos: un árbol de vista de sus discos y particiones de disco -- `lshw`: información de hardware +- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: información de hardware, incluyendo CPU, BIOS, RAID, grafícos, dispositivos, etc. - `fortune`, `ddate`, y `sl`: um, bien, este depende si tiene la consideración de locomotoras de vapor y citas Zippy "práctico" +## Solo para MacOS + +Estos son puntos relevantes *solo* en MacOS. + +- Administración de paquetes con `brew` (Homebrew) y/o `port` (MacPorts). Estos pueden ser utilizados para instalar en MacOS muchos de los comandos de arriba. + +- Copiar la salida de cualquier comando para una aplicación desktop con `pbcopy` y pegar desde una entrada con `pbpaste`. + +- Para abrir un archivo con una applicación desktop, usar `open` o `open -a /Applications/Whatever.app`. + +- Spotlight: Busca archivos con `mdfind` y listar metadata (como información de foto EXIF) con `mdls`. + +- Tenga encuenta que MacOS esta basado en BSD Unix, y cualquier commando (por ejemplo `ps`, `ls`, `tail`, `awk`, `sed`) tiene variaciones discretas variaciones por cada Linux, que esta en gran parte influenciado por el sistema Unix V-style y herramientas GNU. Puedes frecuentemente decirme la diferencia por señalar unas páginas man que tienen el encabezado "BSD General Commands Manual." En algunos casos versiones GNU pueden ser instalados, también (tales como `gawk` y `gsed` para awk y sed del GNU). Si escribe cross-platform scripts Bash, evita tales comandos (por ejemplo, considerando Python o `perl`) o probar con mucho cuidado. + + ## Más recursos - [awesome-shell](https://github.com/alebcay/awesome-shell): Una lista curada de herramientas shell y recursos. @@ -447,4 +471,4 @@ Con excepción de pequeñas tareas, el código está escrito para que otros pued [![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](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/). +Este trabajo esta licenciado bajo [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From 0b7d1287e9532ea7d4c8a3cbf29a6a85d1c46634 Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Fri, 3 Jul 2015 18:06:40 -0400 Subject: [PATCH 22/43] Add Chinese translation for Mac only section Add Chinese translation for Mac only section and fixed some translation error --- README-zh.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/README-zh.md b/README-zh.md index 41e4fb7..dc556ef 100644 --- a/README-zh.md +++ b/README-zh.md @@ -18,7 +18,7 @@ ![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) @@ -432,6 +432,20 @@ - `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否“有用” +## 仅限Mac系统 + +以下是*仅限于* Mac系统的技巧 + +- 用`brew` (Homebrew)或者`port` (MacPorts)进行包管理。这些可以用来在Mac系统上安装以上的大多数命令 + +- 用`pbcopy`复制任何命令的输出到桌面端,用`pbpaste`粘贴从别处的输入 + +- 用`open` 或者 `open -a /Applications/Whatever.app` 通过桌面软件打开文件 + +- Spotlight: 用`mdfind` 搜索文件,用`mdls`列出元数据(例如照片的EXIF信息) + +- 注意Mac系统是基于BSD UNIX的,许多命令(例如`ps`, `ls`, `tail`, `awk`, `sed`)都和Linux中有些微的不同,这些极大的被System V-style Unix和GNU工具影响。你可以通过标题为"BSD General Commands Manual"的man页面发现这些不同。在有些情况下GNU版本的命令也可能被安装(例如`gawk` 和 `gsed` 对应 GNU 中的 awk 和 sed)。如果要写跨平台的Bash脚本,避免使用这些命令(例如,考虑Python或者`perl`)或者仔细的测试。 + ## 更多资源 From 2405ee7065fa998c7848232ddee33d98736c5952 Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Sat, 4 Jul 2015 12:41:45 -0400 Subject: [PATCH 23/43] Fix punctuation and space error for Mac only Section --- README-zh.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-zh.md b/README-zh.md index dc556ef..a7807ee 100644 --- a/README-zh.md +++ b/README-zh.md @@ -432,19 +432,19 @@ - `fortune`,`ddate` 和 `sl`: 额,这主要取决于你是否认为蒸汽火车和莫名其妙的名人名言是否“有用” -## 仅限Mac系统 +## 仅限 Mac 系统 -以下是*仅限于* Mac系统的技巧 +以下是*仅限于* Mac 系统的技巧 -- 用`brew` (Homebrew)或者`port` (MacPorts)进行包管理。这些可以用来在Mac系统上安装以上的大多数命令 +- 用 `brew` (Homebrew)或者 `port` (MacPorts)进行包管理。这些可以用来在 Mac 系统上安装以上的大多数命令 -- 用`pbcopy`复制任何命令的输出到桌面端,用`pbpaste`粘贴从别处的输入 +- 用 `pbcopy` 复制任何命令的输出到桌面端,用 `pbpaste` 粘贴从别处的输入 -- 用`open` 或者 `open -a /Applications/Whatever.app` 通过桌面软件打开文件 +- 用 `open` 或者 `open -a /Applications/Whatever.app` 通过桌面软件打开文件 -- Spotlight: 用`mdfind` 搜索文件,用`mdls`列出元数据(例如照片的EXIF信息) +- Spotlight: 用 `mdfind` 搜索文件,用 `mdls` 列出元数据(例如照片的 EXIF 信息) -- 注意Mac系统是基于BSD UNIX的,许多命令(例如`ps`, `ls`, `tail`, `awk`, `sed`)都和Linux中有些微的不同,这些极大的被System V-style Unix和GNU工具影响。你可以通过标题为"BSD General Commands Manual"的man页面发现这些不同。在有些情况下GNU版本的命令也可能被安装(例如`gawk` 和 `gsed` 对应 GNU 中的 awk 和 sed)。如果要写跨平台的Bash脚本,避免使用这些命令(例如,考虑Python或者`perl`)或者仔细的测试。 +- 注意 Mac 系统是基于 BSD UNIX 的,许多命令(例如 `ps`, `ls`, `tail`, `awk`,`sed`)都和 Linux 中有些微的不同,这些极大的被 System V-style Unix 和 GNU 工具影响。你可以通过标题为 "BSD General Commands Manual" 的 man 页面发现这些不同。在有些情况下 GNU 版本的命令也可能被安装(例如 `gawk` 和 `gsed` 对应 GNU 中的 awk 和 sed )。如果要写跨平台的 Bash 脚本,避免使用这些命令(例如,考虑 Python 或者 `perl` )或者仔细的测试。 ## 更多资源 From 0bf4513e8d8274f7cf993444823baf2feb0e439b Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Sun, 5 Jul 2015 21:35:47 -0400 Subject: [PATCH 24/43] meta & basics sections are translated into Russian --- README-ru.md | 473 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 473 insertions(+) create mode 100644 README-ru.md diff --git a/README-ru.md b/README-ru.md new file mode 100644 index 0000000..73372e7 --- /dev/null +++ b/README-ru.md @@ -0,0 +1,473 @@ +[ На других языках: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] + +# Искусство командной строки + +[![Вступайте в англоязычный чат проекта 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) +- [Основы](#basics) +- [Ежедневное использование](#everyday-use) +- [Процессинг файлов и информации](#processing-files-and-data) +- [Системный дебаггинг](#system-debugging) +- [Команды в одну строчку](#one-liners) +- [Сложно, но полезно](#obscure-but-useful) +- [Только для Маководов](#macos-only) +- [Больше информации по теме](#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) + +Продвинутому использованию командной строки зачастую не уделяют достаточного внимания, о терминале говорят как о чем-то мистическом; на самом же деле это умение очевидно и не очевидно увеличивает Вашу продуктивность в работе. Данный документ является подборкой заметок и советов, которые я нашел для себя полезными, работая с командной строкой в 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), +начав идею там, похоже, что стоит развить ее на Gihub, где обитают люди, которые талантлевее меня и могут предлагать улучения данной подборки. Если Вы заметили ошибки (во всех вариантах перевода), пожалуйста оставьте тикет или киньте пулл-реквест (заранее изучив описание и посмотрев на уже созданнные тикеты и пулл-реквесты). + +## Meta + +Scope: + +- Данная публикация предназначена как для новичков, так и для опытных людей. Цели: *объемность* (собрать все важные аспекты использования командной строки), *практичность* (давать конкретные примеры для самых частых юзкейсов) и *краткость* (не стоит углубляться в неочевидные вещи, о которых можно почитать в другом месте). +- Этот документ написан для пользователей Linux, с единственным исключеним – секцией "[Только для Маководов](#macos-only)". Все остальное подходит и может быть установлено под все UNIX/MacOS системы (и даже Cygwin). +- Фокусируемся на интерактивном Баше, но многие вещи так же могут быть использованы с другими шеллами; и в общем приминимы к Баш-скирптингу +- Эта инструкция включает в себя стандартные Unix комманды и те, для которых нужно устанавливать сторонние пакеты – они настолько полезны, что стоят того, чтобы их установили + +Заметки: + +- Для того, чтобы руководство оставалось одностраничным, вся информация вставлена прямо сюда. Вы достаточно умные для того, чтобы самостоятельно изучить вопрос более детально в другом месте. Используйте `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (в зависимости от вашей системы управления пакетами) для установки новых програм. + +- На [Explainshell](http://explainshell.com/) можно найти простое и детальное объясение того, что такое команды, флаги, пайпы и т.д. + +## Основы + +- Выучите основы Баша. Просто возьмите и напечатайте `man bash` в терминале и хотя бы просмотрите его; он довольно просто читается и он не очень большой. Другие шеллы тоже могут быть хороши, но Баш – мощная программа и Баш всегда под рукой (использование *исключительно* zsh, fish и т.д., которые наверняка круто выглядят на Вашем ноуте во многом Вас ограничивает, например Вы не сможете использовать возможности этих шеллов на уже существующем сервере). + +- Выучите хотя бы один консольный редактор текста. Идеально Vim (`vi`), ведь у него нет конкурентов, когда вам нужно быстренько что-то подправить (даже если Вы постоянно сидите на Emacs/какой-нибудь тяжелой IDE или на каком-нибудь модном хипстерском редакторе) + +- Знайте как читать документацию через `man` (для любознательных – `man man`; `man` по углам документа в скобках добавляет номер, например 1 – для обычных команд, 5 – для файлов, конвенций, 8 – для администативных команд). Ищите мануалы через `apropos`, и помните, что некоторые команды – не бинарники, а встроенные команды Баша, и помощь по ним можно получить через `help` и `help -d`. + +- Узнайте о том, как перенаправлять ввод и вывод через `>` и `<` и пайпы `|`. Помните, что `>` – переписывает выходной файл, а `>>` добавляет к нему. Узнайте побольше про stdout and stderr. + +- Узнайте побольше про file glob expansion with `*` (and perhaps `?` and `{`...`}`), кавычки а так же разницу между двойными `"` и одинарными `'` кавычками. (Больше о расширении переменных читайте ниже) + +- Будьте знакомы с работой с процессами в 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`. + +- Основы работы с сетью: `ip` или `ifconfig`, `dig`. + +- Хорошо знайте регулярные выражения и разные флаги к `grep`/`egrep`. Такие флаги как `-i`, `-o`, `-A`, и `-B` стоит знать. + +- Обучитесь использованию системами управления пакетами `apt-get`, `yum`, `dnf` или `pacman` (в зависимости от дистрибутива). Занйте как искать и устанавливать пакеты и обязательно имейте установленым `pip` для установки командных утилит, написаных на Python (некоторые из тех, что вы найдете ниже легче всего установить через `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. + +- 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. +```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. 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). + +- 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). + +- 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). + + +## 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 + +- `sponge`: read all input before writing it, useful for reading from then writing to the same file, e.g., `grep -v something some-file | sponge some-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 + +- `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`, `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" + + +## 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 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). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully. + + +## 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 b010227d2c307f7381d3b04c3eafc924c5a833fd Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Sun, 5 Jul 2015 21:44:45 -0400 Subject: [PATCH 25/43] couple of fixes to first 2 sections --- README-ru.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README-ru.md b/README-ru.md index 73372e7..a8e8a6a 100644 --- a/README-ru.md +++ b/README-ru.md @@ -13,7 +13,7 @@ - [Сложно, но полезно](#obscure-but-useful) - [Только для Маководов](#macos-only) - [Больше информации по теме](#more-resources) -- [Disclaimer](#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) @@ -26,9 +26,9 @@ на [Quora](http://www.quora.com/What-are-some-time-saving-tips-that-every-Linux-user-should-know), начав идею там, похоже, что стоит развить ее на Gihub, где обитают люди, которые талантлевее меня и могут предлагать улучения данной подборки. Если Вы заметили ошибки (во всех вариантах перевода), пожалуйста оставьте тикет или киньте пулл-реквест (заранее изучив описание и посмотрев на уже созданнные тикеты и пулл-реквесты). -## Meta +## Описание -Scope: +Основное: - Данная публикация предназначена как для новичков, так и для опытных людей. Цели: *объемность* (собрать все важные аспекты использования командной строки), *практичность* (давать конкретные примеры для самых частых юзкейсов) и *краткость* (не стоит углубляться в неочевидные вещи, о которых можно почитать в другом месте). - Этот документ написан для пользователей Linux, с единственным исключеним – секцией "[Только для Маководов](#macos-only)". Все остальное подходит и может быть установлено под все UNIX/MacOS системы (и даже Cygwin). From d09925fb40f7401e5d8c6356528289d9725cda74 Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Sun, 5 Jul 2015 22:41:52 -0400 Subject: [PATCH 26/43] everyday use section is updated --- README-ru.md | 62 ++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/README-ru.md b/README-ru.md index a8e8a6a..6d812de 100644 --- a/README-ru.md +++ b/README-ru.md @@ -66,67 +66,67 @@ - Обучитесь использованию системами управления пакетами `apt-get`, `yum`, `dnf` или `pacman` (в зависимости от дистрибутива). Занйте как искать и устанавливать пакеты и обязательно имейте установленым `pip` для установки командных утилит, написаных на Python (некоторые из тех, что вы найдете ниже легче всего установить через `pip`) -## Everyday use +## Ежедневное использование -- In Bash, use **Tab** to complete arguments and **ctrl-r** to search through command history. +- Используйте таб в Баше для автокомплита аргументов к командам и **ctrl-r** для поиска по истории командной строки -- 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. +- Используйте **ctrl-w** в Баше для того, чтобы удалить последнее слово в команде; **ctrl-u** для того, что бы удалить команду полностью. Используйте **alt-b** и **alt-f** для того, чтобы бегать между словами команды, **ctrl-k** для того, чтобы прыгнуть к концу строки, **ctrl-l** для того, чтобы очистить экран. Гляньте на `man readline` чтобы узнать о всех шорткатах Баша. Их много! Например, **alt-.** бежит по предыдущим аргументам команды, а **alt-*** расширяет глоб.?? -- Alternatively, if you love vi-style key-bindings, use `set -o vi`. +– Если Вам нравятся шорткаты Вима сделайте `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-.**. +- Для того, чтобы посмотреть историю введите `history`. Так же существует множество аббривиатур, например `!$` – последний аргумент, `!!` – последняя команда, хотя эти аббривиатуры часто заменяются шорткатами **ctrl-r** и **alt-.**. -- To go back to the previous working directory: `cd -` +- Для того, чтобы прыгнуть к последней рабочей директории – `cd -` -- If you are halfway through typing a command but change your mind, hit **alt-#** to add a `#` at the beginning and enter it as a comment (or use **ctrl-a**, **#**, **enter**). You can then return to it later via command history. +- Если Вы написали команду наполовину и вдруг передумали нажмите **alt-#** для того, чтобы добавить `#` к началу и отправьте комманду как комментарий. Потом вы сможете вернуться к ней через историю. -- 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: +- Не забывайте использовать `xargs` (или `parallel`). Это очень мощная штука. Обратите внимание, что Вы можете контролировать количество команд на каждую строку, а так же параллельность. Если Вы не уверены, что делаете что-то правильно, начните с `xargs echo`. Еще `-I{}` – полезная штука. Примеры: ```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` – полезный тип вывода дерева процессов. -- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful). +- Используйте `pgrep` или `pkill` для того чтобы находить/слать сигналы к процессам по имени (`-f` помогает). -- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal` +- Знайте разные сигналы, которые можно слать процессам. Например, чтобы приостановить процесс используйте `kill -STOP [pid]`. Для полного списка посмотрите `man 7 signal`. -- Use `nohup` or `disown` if you want a background process to keep running forever. +- Используйте `nohup` или `disown` для того, чтобы процесс в фоне выполнялся бесконечно. -- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP). +- Узнайте какие процессы слушают порты через `netstat -lntp` или `ss -plat` (для TCP; добавьте `-u` для UDP). -- See also `lsof` for open sockets and files. +- Так же `lsof` для того, чтобы посмотреть открытые сокеты и файлы. -- Use `alias` to create shortcuts for commonly used commands. For example, `alias ll='ls -latr'` creates a new alias `ll`. +- Используйте `alias` для того, чтобы алиасить часто используемые команды. Например, `alias ll='ls -latr'` создаст новый алиас `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`. +- В Баш скритах используйте `set -x` для того, чтобы дебажить аутпут. Используйте строгие режимы везде, где возможно. Используйте `set -e` для того, чтобы прекращать выполнение при ошибках. Используйте `set -o pipefail` для того, чтобы строго относится к ошибкам (это немного глубокая тема). Для более сложных скриптов так же используйте `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. +- В Баш скриптах, подоболочки (subshells) – удобный способ группировать команды. Один из самых распространенных примеров – временно передвинуться в другую рабочую директорию, вот так: ```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`. +- В Баше много типов пространства переменных. Проверить, существует ли переменная – `${name:?error message}`. Например, если Баш-скрипту нужен всего один аргумент просто напишите `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`. -- The output of a command can be treated like a file via `<(some command)`. For example, compare local `/etc/hosts` with a remote one: +- Вывод любой команды можно обратить в файл через `<(some command)`. Например, сравнение локального файла `/etc/hosts с удаленным: ```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`. Зачастую для того, чтобы убедится, что команда не оставит открытым файл, привязав его к открытому терминалу считается хорошей практикой добавлять ` Date: Sun, 5 Jul 2015 22:50:45 -0400 Subject: [PATCH 27/43] last 3 sections translated --- README-ru.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/README-ru.md b/README-ru.md index 6d812de..e1b7a32 100644 --- a/README-ru.md +++ b/README-ru.md @@ -455,19 +455,21 @@ These are items relevant *only* on MacOS. - 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 +## Больше информации по теме -- [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): Дополняемый список инструментов и ресурсов для командной строки. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) Для того, чтобы писать шелл-скрипты лучше. -## 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! ;) +За небольшим исключением, весь код написан так, что другие его смогут прочитать. + +With the exception of very small tasks, code is written so others can read it. Кому много дано, с того много и спрашивается. Тот факт, что что-то может быть написано в Баше, вовсе не означает что оно должно быть там написано. ;) -## 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/). +Оригинальная работа и перевод на русский язык распространяется под лицензией [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From 745036b559e8c89a7e71460266a96d1c17e540da Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Mon, 6 Jul 2015 22:26:57 -0400 Subject: [PATCH 28/43] halfway through file processing section --- README-ru.md | 55 ++++++++++++++++++++++++++++------------------------ 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/README-ru.md b/README-ru.md index e1b7a32..e5a4bf8 100644 --- a/README-ru.md +++ b/README-ru.md @@ -11,7 +11,7 @@ - [Системный дебаггинг](#system-debugging) - [Команды в одну строчку](#one-liners) - [Сложно, но полезно](#obscure-but-useful) -- [Только для Маководов](#macos-only) +- [MacOS only](#macos-only) - [Больше информации по теме](#more-resources) - [Дисклеймер](#disclaimer) @@ -31,7 +31,7 @@ Основное: - Данная публикация предназначена как для новичков, так и для опытных людей. Цели: *объемность* (собрать все важные аспекты использования командной строки), *практичность* (давать конкретные примеры для самых частых юзкейсов) и *краткость* (не стоит углубляться в неочевидные вещи, о которых можно почитать в другом месте). -- Этот документ написан для пользователей Linux, с единственным исключеним – секцией "[Только для Маководов](#macos-only)". Все остальное подходит и может быть установлено под все UNIX/MacOS системы (и даже Cygwin). +- Этот документ написан для пользователей Linux, с единственным исключеним – секцией "[MacOS only](#macos-only)". Все остальное подходит и может быть установлено под все UNIX/MacOS системы (и даже Cygwin). - Фокусируемся на интерактивном Баше, но многие вещи так же могут быть использованы с другими шеллами; и в общем приминимы к Баш-скирптингу - Эта инструкция включает в себя стандартные Unix комманды и те, для которых нужно устанавливать сторонние пакеты – они настолько полезны, что стоят того, чтобы их установили @@ -154,54 +154,57 @@ - Для того, чтобы выполнить определенную команду с привилегиями, используйте `sudo` (для рута) и `sudo -u` (для другого пользователя). Используйте `su` или `sudo bash` для того чтобы запустить шелл от имени этого пользователя. Используйте `su -` для того, чтобы симулировать свежий логин от рута или другого пользователя. -## Processing files and data +## Процессинг файлов и информации -- To locate a file by name in the current directory, `find . -iname '*something*'` (or similar). To find a file anywhere by name, use `locate something` (but bear in mind `updatedb` may not have indexed recently created files). +- Для того, чтобы найти файл в текущей директории сделайте `find . -iname '*something*'`. Для того, чтобы искать файл по всей системе используйте `locate something` (но не забывайте, что `updatedb` мог еще не проидексировать недавно созданные файлы). -- For general searching through source or data files (more advanced than `grep -r`), use [`ag`](https://github.com/ggreer/the_silver_searcher). +- Для основого поиска по содержимому файлов (более сложному, чем `grep -r`) используйте [`ag`](https://github.com/ggreer/the_silver_searcher). -- To convert HTML to text: `lynx -dump -stdin` +- Для конвертации HTML в текст: `lynx -dump -stdin` -- For Markdown, HTML, and all kinds of document conversion, try [`pandoc`](http://pandoc.org/). +- Для конвертации разных типов разметки (HTML, маркдаун и т.д.) попробуйте [`pandoc`](http://pandoc.org/). -- If you must handle XML, `xmlstarlet` is old but good. +- Если нужно работать с XML, есть старая но хорошая утилита – `xmlstarlet`. -- For JSON, use `jq`. +- Для работы с JSON используйте `jq`. -- For Excel or CSV files, [csvkit](https://github.com/onyxfish/csvkit) provides `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc. +- Для работы с Excel и CSV-файлами используйте [csvkit](https://github.com/onyxfish/csvkit) (программа предоставляет команды `in2csv`, `csvcut`, `csvjoin`, `csvgrep` и т.д.) -- 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. +- Для работы с Amazon S3 удобно работать с [`s3cmd`](https://github.com/s3tools/s3cmd) и [`s4cmd`](https://github.com/bloomreach/s4cmd) (последний работает быстрее). Для остальных сервисов Амазона используйте стандартный [`aws`](https://github.com/aws/aws-cli). -- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. See also `comm`. +- Знайте про `sort` и `uniq`, включая флаги `-u` и `-d`, смотрите примеры ниже. Еще гляньте на `comm`. -- Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`. +- Знайте про `cut`, `paste`, и `join` для работы с текстовыми файлами. Многие люди используют `cut` забыв про `join`. -- Know about `wc` to count newlines (`-l`), characters (`-m`), words (`-w`) and bytes (`-c`). +- Знайте о `wc`: для подсчета переводов строк (`-l`), для символов – (`-m`), для слов – words (`-w`), для байтового подсчета – (`-c`). -- Know about `tee` to copy from stdin to a file and also to stdout, as in `ls -al | tee file.txt`. +- Знайте про `tee`, для копирования в файл из stdin и stdout, что-то типа `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`. +- Не забывайте, что Ваша локаль влияет на многие команды, включая порядки сортировки, сравнение и производительность. Многие дистрибутивы Linux автоматически выставляют `LANG` или любую другую переменную в подходящую для Вашего региона. Из-за этого результаты функций сортировки могут работать непредсказуемо. Рутины `i18n` могут значительно снизить производительность сортировок. В некоторых случаях можно полностью этого избегать (за исключением редких случаев), сортируя традиционно побайтово, для этого `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. +- Знайте основы `awk` и `sed` для простых манипуляций с данными. Например, чтобы получить сумму всех чисел, которые находятся в третьей колонки текстового файла можно использовать `awk '{ x += $3 } END { print x }'`. Скорее всего, это раза в 3 быстрее и раза в 3 проще чем делать это в Питоне. -- To replace all occurrences of a string in place, in one or more files: +- Чтобы заменить все нахождения подстроки в одном или нескольких файлах: ```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. +Для того, чтобы переименовать сразу много файлов по шаблону, используйте `rename`. Для сложных переименований может помочь [`repren`](https://github.com/jlevy/repren): + ```sh - # Recover backup files foo.bak -> foo: + # Восстановить бекапы из foo.bak в foo: rename 's/\.bak$//' *.bak - # Full rename of filenames, directories, and contents foo -> bar: + # Полное переименование имен файлов, папок и содержимого файлов из foo в bar. repren --full --preserve-case --from foo --to bar . ``` -- Use `shuf` to shuffle or select random lines from a file. +- Используйте `shuf` для того, чтобы перемешать строки или выбрать случайную строчку из файла. + +- Знайте флаги `sort`а. Для чисел используйте `-n`, для работы с человекочитаемыми числами используйте `-h` (например `du -h`). Знайте как работают ключи (`-t` и `-k`). В частности, не забывайте что вам нужно писать `-k1,1` для того, чтобы отсортировать только первое поле; `-k1` значит сортировка учитывая всю строчку. Так же стабильная сортировка может быть полезной (`sort -s`). Например для того, чтобы отсортировать самое важное по второму полю, а второстепенное по первому можно использовать sort -k1,1 | sort -s -k2,2`. + +- Если вам когда-нибудь придется написать код таба в терминале, например для сортировки по табу с флагом -t, используйте шорткат **ctrl-v** **[Tab]** или напишите `$'\t'`. Последнее лучше, потому что его можно скопировать. -- 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). - 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. @@ -443,8 +446,10 @@ A few examples of piecing together commands: ## MacOS only These are items relevant *only* on MacOS. +Некоторые вещи релевантны только для Мака. + +- Системы управлением пакетами – `brew` (Homebrew) и `port` (MacPorts). Они могут быть использованы для того, чтобы установить большинство програм, упомянутых в этом документе. -- 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 to a desktop app with `pbcopy` and paste input from one with `pbpaste`. From 14b44e8221a8c84989e502258c1477d1a745734d Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Mon, 6 Jul 2015 22:46:23 -0400 Subject: [PATCH 29/43] file processing finished & macos section corrected --- README-ru.md | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/README-ru.md b/README-ru.md index e5a4bf8..cc3b874 100644 --- a/README-ru.md +++ b/README-ru.md @@ -204,25 +204,23 @@ - Если вам когда-нибудь придется написать код таба в терминале, например для сортировки по табу с флагом -t, используйте шорткат **ctrl-v** **[Tab]** или напишите `$'\t'`. Последнее лучше, потому что его можно скопировать. +- Стандартные инструменты для патчинга исходников это `diff` и `patch`. Так же посмотрите на `diffstat` для просмотра статистики диффа. `diff -r` работает для по всей директории. Используйте `diff -r tree1 tree2 | diffstat` для полной сводки изменений. +- Для бинарников используйте `hd` для простых hex-дампом и `bvi` для двоичного изменения бинарников. -- 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. +- `strings` (в связке `grep` или чем-то похожем) помогает найти строки в бинарниках. -- For binary files, use `hd` for simple hex dumps and `bvi` for binary editing. +- Для того, чтобы посмотреть разницу в бинарниках (дельта кодирование) используйте `xdelta3`. -- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text. +- Для конвертирования кодировок используйте `iconv`. Для более сложных задач – `uconv`, он поддерживает некоторые сложные фичи Юникода. Например эта команда переводит строки из файла в нижний регистр и убирает ударения (кои бывают, например, в Испанском) -- 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. +- Для того, чтобы разбить файл на куски используйте `split` (разбивает на куски по размеру), или `csplit` (по шаблону или регулярному выражению) +- Используйте `zless`, `zmore`, `zcat`, и `zgrep` для работы с сжатыми файлами. ## System debugging @@ -445,20 +443,17 @@ A few examples of piecing together commands: ## MacOS only -These are items relevant *only* on MacOS. -Некоторые вещи релевантны только для Мака. +Некоторые вещи релевантны *только* для Мака. - Системы управлением пакетами – `brew` (Homebrew) и `port` (MacPorts). Они могут быть использованы для того, чтобы установить большинство програм, упомянутых в этом документе. +- Копируйте аутпут консольных программ в десктопные через `pbcopy`, и вставляйте инпут через `pbpaste`. -- Copy output of any command to a desktop app with `pbcopy` and paste input from one with `pbpaste`. +- Для того, чтобы открыть файл или десктопную программу типа Finder используйте `open`, вот так `open -a /Applications/Whatever.app`. -- 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). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully. +- Spotlight: Ищите файлы в консоле через `mdfind` и смотрите метадату (например EXIF информацию фотографий) через `mdls`. +- Не забывайте, что MacOS основан на BSD Uni и многие команды (например `ps`, `ls`, `tail`, `awk`, `sed`) имеют некоторые небольшие различия с линуксовыми. Это обусловлено влянием `UNIX System V` и `GNU Tools`. Разницу можно заметить увидив заголовок "BSD General Commands Manual." к манам програм. В некоторых случаях, на Мак можно поставить GNU-версии программ, например `gawk` и `gsed`. Когда пишите кроссплатформенные Bash-скрипты, старайтесь избегать команды, которые могут различаться (например, лучше используйте Python или `perl`), или тщательно все тестируйте. ## Больше информации по теме @@ -470,7 +465,7 @@ These are items relevant *only* on MacOS. За небольшим исключением, весь код написан так, что другие его смогут прочитать. -With the exception of very small tasks, code is written so others can read it. Кому много дано, с того много и спрашивается. Тот факт, что что-то может быть написано в Баше, вовсе не означает что оно должно быть там написано. ;) +Кому много дано, с того много и спрашивается. Тот факт, что что-то может быть написано в Баше, вовсе не означает что оно должно быть там написано. ;) ## Лицензия From 31c6d4f7dadaf10ee841ce907c0c56b637349e71 Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Mon, 6 Jul 2015 23:13:53 -0400 Subject: [PATCH 30/43] one liners translated --- README-ru.md | 58 ++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/README-ru.md b/README-ru.md index cc3b874..7e32637 100644 --- a/README-ru.md +++ b/README-ru.md @@ -9,7 +9,7 @@ - [Ежедневное использование](#everyday-use) - [Процессинг файлов и информации](#processing-files-and-data) - [Системный дебаггинг](#system-debugging) -- [Команды в одну строчку](#one-liners) +- [В одну строчку](#one-liners) - [Сложно, но полезно](#obscure-but-useful) - [MacOS only](#macos-only) - [Больше информации по теме](#more-resources) @@ -222,48 +222,47 @@ - Используйте `zless`, `zmore`, `zcat`, и `zgrep` для работы с сжатыми файлами. -## 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). +- Дле веб-дебаггинга используйте `curl` и `curl -I`, или их альтернативу `wget`. Так же есть более современные альтернативы, типа [`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. +- Чтобы получить информацию о диске/CPU/сети используйте `iostat`, `netstat`, `top` (или лучшую альтернатву `htop`) и особенно `dstat`. Хороший старт для того, чтобы понимать что происходит в системе. -- 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. +- Для более детальной информации используйте [`glances`](https://github.com/nicolargo/glances). Эта программа показывает сразу несколько разных статистик в одном окне терминале. Полезно, когда следите за сразу несколькими системами. -- 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. +- Для того, чтобы следить за памятью научитесь понимать `free` и `vmstat`. В частности не забывайте, что кешированые значения ("cached" value) – это память, которую держит ядро и эти значения являются частью `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. +- Дебаггинг Джавы – совсем другая рыбка, но некоторые манипуляции над виртуальной машиной Оракла или любой другой позволит вам использовать делать `kill -3 ` и трассировать сводки стека и хипа (включая детали работы сборщика мусора, которые бывают очень полезными), и их можно дампнуть в stderr или логи. -- Use `mtr` as a better traceroute, to identify network issues. +- Используйте `mtr` для лучшей трассировки, чтобы находить проблемы сети. -- For looking at why a disk is full, `ncdu` saves time over the usual commands like `du -sh *`. +- Для того, чтобы узнать почему диск полностью забит используйте `ncdu`, это сохраняет время по сравнению с тем же `du -sh *`. -- To find which socket or process is using bandwidth, try `iftop` or `nethogs`. +- Для того, чтобы узнать какой сокет или процесс использует интернет используйте `iftop` или `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`. +- `ab`, которая поставляется вместе в Апачем полезна для быстрой нетщательной проверки производительности веб-сервера. Для более серьезного лоад-тестинга используйте `siege`. -- For more serious network debugging, `wireshark`, `tshark`, or `ngrep`. +- Для более серьезного дебаггинга сетей используйте `wireshark`, `tshark`, и `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`). +- Знайте про `strace` и `ltrace`. Эти команды могут быть полезны, если программа падает или висит и вы не знаете почему, или если вы хотите протестировать производительность программы. Не забывайте про возможность дебаггинга (`-c`) и возможностью прицепиться к процессу (`-p`). -- Know about `ldd` to check shared libraries etc. +- Не забывайте про `ldd` для проверки системных библиотек. -- Know how to connect to a running process with `gdb` and get its stack traces. +- Знайте как прицепиться к бегущему процессу через `gdb` и получить трассировку стека. -- 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`. +- Используйте `/proc`. Иногда он невероятно полезен для дебага запущенных программ. Примеры: `/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. +- Когда дебажете что-то, что сломалось в прошлом используйте `sar` – бывает очень полезно. Показывает историю CPU, памяти, сети и т.д. -- 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). +- Для анализа более глубоких систем и производительности посмотрите на `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](http://en.wikipedia.org/wiki/Perf_(Linux)), и [`sysdig`](https://github.com/draios/sysdig). -- Check what OS you're on with `uname` or `uname -a` (general Unix/kernel info) or `lsb_release -a` (Linux distro info). +- Узнайте какая у вас операционка через `uname` or `uname -a` (основная Unix-информация/информация о ядре) или `lsb_release -a` (информация о дистрибутиве). -- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues). +- Используйте `dmesg` когда что-то ведет себя совсем странно (например железо или драйвера). +## В одну строчку -## 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 @@ -272,31 +271,32 @@ A few examples of piecing together commands: 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`. +- Используйте `grep . *` для того, чтобы визуально посмотреть что находится в директории, особенно послезно когда у вас много конфигов типа `/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): +- Получить сумму всех чисел, которые находятся в третьей колонки текстового файла. (Скорее всего, это раза в 3 быстрее и раза в 3 проще чем делать это в Питоне): ```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 ``` +Это почти как рекурсивная `ls -l, но более читабельно чем `ls -lR`: -- 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: +- Используйте `xargs` (или `parallel`). Это очень мощная штука. Обратите внимание, что Вы можете контролировать количество команд на каждую строку, а так же параллельность. Если Вы не уверены, что делаете что-то правильно, начните с `xargs echo`. Еще `-I{}` – полезная штука. Примеры: ```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`: +- Давайте представим, что у нас есть какой-то текстовый файл, например лог какого-то сервера и на каких-то строках появляется значение, строки с которой нам интересны, например `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 | From 3c882424dd2f1227e3a6976ee6c294294ad51888 Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Tue, 7 Jul 2015 00:00:58 -0400 Subject: [PATCH 31/43] first version of russian translation --- README-ru.md | 141 +++++++++++++++++++++++++-------------------------- 1 file changed, 70 insertions(+), 71 deletions(-) diff --git a/README-ru.md b/README-ru.md index 7e32637..9229936 100644 --- a/README-ru.md +++ b/README-ru.md @@ -72,7 +72,7 @@ - Используйте **ctrl-w** в Баше для того, чтобы удалить последнее слово в команде; **ctrl-u** для того, что бы удалить команду полностью. Используйте **alt-b** и **alt-f** для того, чтобы бегать между словами команды, **ctrl-k** для того, чтобы прыгнуть к концу строки, **ctrl-l** для того, чтобы очистить экран. Гляньте на `man readline` чтобы узнать о всех шорткатах Баша. Их много! Например, **alt-.** бежит по предыдущим аргументам команды, а **alt-*** расширяет глоб.?? -– Если Вам нравятся шорткаты Вима сделайте `set -o vi`. +- Если Вам нравятся шорткаты Вима сделайте `set -o vi`. - Для того, чтобы посмотреть историю введите `history`. Так же существует множество аббривиатур, например `!$` – последний аргумент, `!!` – последняя команда, хотя эти аббривиатуры часто заменяются шорткатами **ctrl-r** и **alt-.**. @@ -264,14 +264,14 @@ Давайте соберем все вместе и напишем несколько комманд: -- 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). +- Это довольно круто, что можно найти множественные пересечения файлов, соединить отсортированные файлы и посмотреть разницу в нескольких файлов через `sort`/`uniq`. Это быстрый подход и работает на файлах любого размера (включая многогигабайтные файлы). (Сортировка не ограничена памятью, но возможно вам придется добавить `-T` если `/tmp` находится на небольшом логическом диске). Еще посмотрите то что было сказано выше о `LC_ALL`. Флаг сорта `-u` option не используется ниже чтобы было понятнее: ```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 | 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`. - Получить сумму всех чисел, которые находятся в третьей колонки текстового файла. (Скорее всего, это раза в 3 быстрее и раза в 3 проще чем делать это в Питоне): @@ -308,138 +308,137 @@ ``` -## Obscure but useful +## Сложно, но полезно -- `expr`: perform arithmetic or boolean operations or evaluate regular expressions +- `expr`: для выполнения арифметических и булевых операций, а так же регулярных выражений -- `m4`: simple macro processor +- `m4`: простенький макро-процессор -- `yes`: print a string a lot +- `yes`: вывод строки в бесконечном цикле -- `cal`: nice calendar +- `cal`: классный календарь -- `env`: run a command (useful in scripts) +- `env`: для того, чтобы выполнить команду (полезно в Bash-скриптах) - `printenv`: print out environment variables (useful in debugging and scripts) -- `look`: find English words (or lines in a file) beginning with a string +- `look`: найти английские слова (или строки) в файле -- `cut `and `paste` and `join`: data manipulation +- `cut `, `paste` и `join`: манипуляция данными -- `fmt`: format text paragraphs +- `fmt`: форматировка параграфов в тексте -- `pr`: format text into pages/columns +- `pr`: отформатировать текст в страницы/колонки -- `fold`: wrap lines of text +- `fold`: (обернуть) ограничить длину строк в файле -- `column`: format text into columns or tables +- `column`: форматировать текст в колонки или таблицы -- `expand` and `unexpand`: convert between tabs and spaces +- `expand` и `unexpand`: конвертация между табами и пробелами -- `nl`: add line numbers +- `nl`: добавить номера строк -- `seq`: print numbers +- `seq`: вывести числа -- `bc`: calculator +- `bc`: калькулятор -- `factor`: factor integers +- `factor`: возвести числа в степень -- `gpg`: encrypt and sign files +- `gpg`: зашифровать и подписать файлы -- `toe`: table of terminfo entries +- `toe`: таблица терминалов terminfo с описанием -- `nc`: network debugging and data transfer +- `nc`: дебаггинг сети и передачи данных -- `socat`: socket relay and tcp port forwarder (similar to `netcat`) +- `socat`: переключатель сокетов и перенаправление tcp-портов (похоже на `netcat`) -- `slurm`: network trafic visualization +- `slurm`: визуализация трафика сети -- `dd`: moving data between files or devices +- `dd`: перенос информации между файлами и девайсами -- `file`: identify type of a file +- `file`: узнать тип файла -- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive +- `tree`: показать директории и сабдиректории в виде дерева; как `ls`, но рекурсивно -- `stat`: file info +- `stat`: информация о файле -- `tac`: print files in reverse +- `tac`: вывести файл наоборот (ласипан) -- `shuf`: random selection of lines from a file +- `shuf`: случайная выборка строк из файла -- `comm`: compare sorted files line by line +- `comm`: построчно сравнить отсортированные файлы -- `pv`: monitor the progress of data through a pipe +- `pv`: мониторинг прогресса прохождения информации через пайп -- `hd` and `bvi`: dump or edit binary files +- `hd` и `bvi`: дамп и редактирование бинарников -- `strings`: extract text from binary files +- `strings`: найти текст в бинарникх -- `tr`: character translation or manipulation +- `tr`: манипуляция с char (символьным типом) -- `iconv` or `uconv`: conversion for text encodings +- `iconv` и `uconv`: конвертация кодировок -- `split `and `csplit`: splitting files +- `split` и `csplit`: разбить файлы -- `sponge`: read all input before writing it, useful for reading from then writing to the same file, e.g., `grep -v something some-file | sponge some-file` +- `sponge`: прочитать весь инпут перед тем, как его записать, полезно когда читаешь из того же файла, куда записываешь, например вот так: `grep -v something some-file | sponge some-file` -- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`) +- `units`: конвертер, метры в келометры, версты в пяди (смотрите `/usr/share/units/definitions.units`) -- `7z`: high-ratio file compression +- `7z`: архиватор с высокой степенью сжатия -- `ldd`: dynamic library info +- `ldd`: показывает зависимости программы от системных библиотек -- `nm`: symbols from object files +- `nm`: получаем названия всех функций, которые определены в .o или .a -- `ab`: benchmarking web servers +- `ab`: бенчмаркинг веб-серверов -- `strace`: system call debugging +- `strace`: дебаг системных вызовов -- `mtr`: better traceroute for network debugging +- `mtr`: лучшей трассировка для дебаггинга сети -- `cssh`: visual concurrent shell +- `cssh`: несколько терминалов в одном UI -- `rsync`: sync files and folders over SSH +- `rsync`: синхронизация файлов и папок через SSH -- `wireshark` and `tshark`: packet capture and network debugging +- `wireshark` и `tshark`: перехват пакетов и дебаг сети -- `ngrep`: grep for the network layer +- `ngrep`: grep для слоя сети (network layer) -- `host` and `dig`: DNS lookups +- `host` и `dig`: узнать DNS -- `lsof`: process file descriptor and socket info +- `lsof`: процессинг дискрипторов и информация о сокетах -- `dstat`: useful system stats +- `dstat`: полезная статистика системы -- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview +- [`glances`](https://github.com/nicolargo/glances): высокоуровневая, многосистемная статистика -- `iostat`: CPU and disk usage stats +- `iostat`: статистика CPU и использования жесткого диска -- `htop`: improved version of top +- `htop`: улучшенная версия top -- `last`: login history +- `last`: история логинов в систему -- `w`: who's logged on +- `w`: под каким пользователем вы сидите -- `id`: user/group identity info +- `id`: информация о пользователе/группе -- `sar`: historic system stats +- `sar`: история системной статистики -- `iftop` or `nethogs`: network utilization by socket or process +- `iftop` или `nethogs`: использование сети конкретным сокетом или процессом -- `ss`: socket statistics +- `ss`: статистика сокетов -- `dmesg`: boot and system error messages +- `dmesg`: ошибки бута и ошибки системы -- `hdparm`: SATA/ATA disk manipulation/performance +- `hdparm`: манипуляция с SATA/ATA -- `lsb_release`: Linux distribution info +- `lsb_release`: информация о дистрибутиве Linux -- `lsblk`: List block devices: a tree view of your disks and disk paritions +- `lsblk`: cписок блочных устройств компьютера: древо ваших дисков и логических дисков -- `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" +- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: информация о железе включая, CPU, BIOS, RAID, графику, девайсы, и т.д. +- `fortune`, `ddate`, и `sl`: хм, не знаю будут ли вам "полезны" веселые цитатки и поезда, пересекающие ваш терминал :) ## MacOS only From a70ba3323e2f25c77f8bd22b286c15f80f375d25 Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Tue, 7 Jul 2015 00:03:44 -0400 Subject: [PATCH 32/43] add links to russian translation everywhere --- README-es.md | 12 +++--- README-pt.md | 108 +++++++++++++++++++++++++-------------------------- README-zh.md | 2 +- README.md | 6 +-- 4 files changed, 64 insertions(+), 64 deletions(-) diff --git a/README-es.md b/README-es.md index 3014e04..e6ec203 100644 --- a/README-es.md +++ b/README-es.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [Español](README-es.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), [Русский](README-ru.md) ] # El Arte del Terminal @@ -25,8 +25,8 @@ Gran parte esta [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: @@ -34,7 +34,7 @@ Alcance: - 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, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros Unices o 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. +- 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. Notas: @@ -384,7 +384,7 @@ Algunos ejemplos de comandos reunidos: - `units`: unidades de conversión y calculaciones; convierte furlongs por fortnight para twips por blink (ver también `/usr/share/units/definitions.units`) -- `7z`: conpresión de archivos de alto nivel +- `7z`: conpresión de archivos de alto nivel - `ldd`: información de libreria dinamica @@ -469,6 +469,6 @@ Con excepción de pequeñas tareas, el código está escrito para que otros pued ## Licencia -[![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/) Este trabajo esta licenciado bajo [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). diff --git a/README-pt.md b/README-pt.md index a85c14f..db5f8ea 100644 --- a/README-pt.md +++ b/README-pt.md @@ -1,7 +1,7 @@ -[ Languages: [English](README.md), [Español](README-es.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), [Русский](README-ru.md) ] -# A arte da linha de comando +# A arte da linha de comando - [Meta](#meta) - [Básico](#básico) @@ -30,15 +30,15 @@ Escopo: - 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. +- 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 ú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. +- Use [Explainshell](http://explainshell.com/) para encontrar informações úteis sobre o que fazem os comandos, as opções, pipes e etc. -## Básico +## 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 você usa o seu próprio notebook, mas restringe você em muitas situações, por exemplo quando você quer usar servidores de outros). @@ -63,11 +63,11 @@ 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 das abaixo são mais fáceis de instalar através do `pip`). -## Uso diário +## Uso diário - Usando Bash, use **Tab** para completar argumentos e **ctrl-r** para pesquisar através a história dos comandos. -- 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. +- 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`. @@ -111,7 +111,7 @@ Notas: diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` -- Saiba sobre "documentos aqui" no Bash, como em `cat <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 `` 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. @@ -302,19 +302,19 @@ Alguns exemplos de como reunir os comandos. ``` -## Obscuros mas úteis +## Obscuros mas úteis -- `expr`: executa operações boleanas ou aritméticas ou avalia expressões regulares. +- `expr`: executa operações boleanas ou aritméticas ou avalia expressões regulares. -- `m4`: simples processador de macros. +- `m4`: simples processador de macros. -- `yes`: imprime uma string muitas vezes. +- `yes`: imprime uma string muitas vezes. -- `cal`: calendário legal. +- `cal`: calendário legal. - `env`: executa um comando (útil em scripts). -- `printenv`: imprime as variáveis de ambiente (útil em debug e scripts). +- `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. @@ -328,69 +328,69 @@ Alguns exemplos de como reunir os comandos. - `column`: formata texto em colunas ou tabelas. -- `expand` e `unexpand`: converte entre tabs e espaços. +- `expand` e `unexpand`: converte entre tabs e espaços. -- `nl`: adiciona números as linhas. +- `nl`: adiciona números as linhas. -- `seq`: imprime números. +- `seq`: imprime números. -- `bc`: calculadora. +- `bc`: calculadora. -- `factor`: fatora inteiros. +- `factor`: fatora inteiros. -- `gpg`: criptografa e assina arquivos. +- `gpg`: criptografa e assina arquivos. -- `toe`: tabela de entradas dos tipos de terminais. +- `toe`: tabela de entradas dos tipos de terminais. -- `nc`: ferramenta de debug de rede e transferência de dados. +- `nc`: ferramenta de debug de rede e transferência de dados. - `socat`: socket relay e encaminhamento de portas tcp (similar ao `netcat`) -- `slurm`: visualização do tráfego da rede. +- `slurm`: visualização do tráfego da rede. - `dd`: move os dados entre arquivos ou dispositivos. -- `file`: identifica o tipo do arquivo. +- `file`: identifica o tipo do arquivo. -- `tree`: mostra os diretórios e subdiretórios como um árvore de dependências; como `ls` mas recursivo. +- `tree`: mostra os diretórios e subdiretórios como um árvore de dependências; como `ls` mas recursivo. -- `stat`: informações do arquivo. +- `stat`: informações do arquivo. -- `tac`: imprime arquivos na ordem reversa. +- `tac`: imprime arquivos na ordem reversa. - `shuf`: seleção random de linhas de um arquivo. -- `comm`: compara uma lista de arquivos ordenadas linha por linha. +- `comm`: compara uma lista de arquivos ordenadas linha por linha. -- `pv`: monitora o progresso dos dados através de um pipe. +- `pv`: monitora o progresso dos dados através de um pipe. - `hd` e `bvi`: dump ou edita arquivos binários. - `strings`: extrai texto de arquivos binários. -- `tr`: tradução e manipulação de caracteres. +- `tr`: tradução e manipulação de caracteres. - `iconv` ou `uconv`: conversor de codificações de texto. -- `split ` e `csplit`: divisão de arquivos. +- `split ` e `csplit`: divisão de arquivos. - `units`: conversor de unidades e cálculos; converte furlongs por quinzena para twips per blink (veja também `/usr/share/units/definitions.units`) - `7z`: Compressor de arquivos de alto desempenho. -- `ldd`: informações dinâmicas das bibliotecas. +- `ldd`: informações dinâmicas das bibliotecas. - `nm`: símbolos de arquivos objetos. - `ab`: benchmarking para web servers. -- `strace`: Debug para chamadas de sistema. +- `strace`: Debug para chamadas de sistema. - `mtr`: melhor traceroute para debugar a rede. - `cssh`: Visualização concorrente da shell. -- `rsync`: Sincroniza arquivos e pastas através do SSH. +- `rsync`: Sincroniza arquivos e pastas através do SSH. - `wireshark` e `tshark`: captura de pacotes e debug de rede. @@ -398,25 +398,25 @@ Alguns exemplos de como reunir os comandos. - `host` e `dig`: Consultas DNS. -- `lsof`: Arquivo de descritores dos processos e informações dos sockets. +- `lsof`: Arquivo de descritores dos processos e informações dos sockets. -- `dstat`: Estatísticas úteis do sistema. +- `dstat`: Estatísticas úteis do sistema. -- [`glances`](https://github.com/nicolargo/glances): Resumo de 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. +- `iostat`: Estatísticas de uso do CPU e do disco. -- `htop`: Versão do top melhorada. +- `htop`: Versão do top melhorada. -- `last`: histórico de logins. +- `last`: histórico de logins. -- `w`: quem está logado. +- `w`: quem está logado. -- `id`: Informações sobre a identidade do user/group. +- `id`: Informações sobre a identidade do user/group. -- `sar`: histórico dos estados do sistema. +- `sar`: histórico dos estados do sistema. -- `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. +- `iftop` ou `nethogs`: Utilização da rede por sockets ou processos. - `ss`: Estatísticas dos sockets. @@ -430,20 +430,20 @@ Alguns exemplos de como reunir os comandos. - `lshw` e `lspci`: informações do hardware, incluindo RAID, gráficos, etc. -- `fortune`, `ddate`, e `sl`: um, bem, isto depende de você considerar locomotivas a vapor e citações Zippy "úteis". +- `fortune`, `ddate`, e `sl`: um, bem, isto depende de você considerar locomotivas a vapor e citações Zippy "úteis". -## Mais conteúdo +## Mais conteúdo - [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. +- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) para escrever shell scripts melhores. -## Aviso +## Aviso 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 +## Licença -[![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/) Este trabalho está licenciado com uma [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). diff --git a/README-zh.md b/README-zh.md index 41e4fb7..98b2930 100644 --- a/README-zh.md +++ b/README-zh.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [Español](README-es.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), [Русский](README-ru.md) ] # 命令行的艺术 diff --git a/README.md b/README.md index 13f8e6b..327bdf6 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[ Languages: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] +[ [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md), [Русский](README-ru.md) ] @@ -36,7 +36,7 @@ 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, 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. +- 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: @@ -471,6 +471,6 @@ With the exception of very small tasks, code is written so others can read it. W ## License -[![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/) This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/). From cafe2316a9d5aa9d59b0057e0426c50b32212dac Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Tue, 7 Jul 2015 00:24:18 -0400 Subject: [PATCH 33/43] fixed anchors in Russian version --- README-ru.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README-ru.md b/README-ru.md index 9229936..5f0102c 100644 --- a/README-ru.md +++ b/README-ru.md @@ -1,19 +1,19 @@ -[ На других языках: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md) ] +[ На других языках: [English](README.md), [Español](README-es.md), [Português](README-pt.md), [中文](README-zh.md), [Русский](README-ru.md) ] # Искусство командной строки [![Вступайте в англоязычный чат проекта 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) -- [Основы](#basics) -- [Ежедневное использование](#everyday-use) -- [Процессинг файлов и информации](#processing-files-and-data) -- [Системный дебаггинг](#system-debugging) -- [В одну строчку](#one-liners) -- [Сложно, но полезно](#obscure-but-useful) +- [Описание](#описание) +- [Основы](#основы) +- [Ежедневное использование](#ежедневное-использование) +- [Процессинг файлов и информации](#процессинг-файлов-и-информации) +- [Системный дебаггинг](#системный-дебаггинг) +- [В одну строчку](#В-одну-строчку) +- [Сложно, но полезно](#Сложно,-но-полезно) - [MacOS only](#macos-only) -- [Больше информации по теме](#more-resources) -- [Дисклеймер](#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) From 96d7801be716491094e4b6df16149432a6f72390 Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Tue, 7 Jul 2015 00:26:44 -0400 Subject: [PATCH 34/43] anchor issue resolved --- README-ru.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README-ru.md b/README-ru.md index 5f0102c..f7f3c8c 100644 --- a/README-ru.md +++ b/README-ru.md @@ -4,16 +4,16 @@ [![Вступайте в англоязычный чат проекта 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) -- [Описание](#описание) -- [Основы](#основы) -- [Ежедневное использование](#ежедневное-использование) -- [Процессинг файлов и информации](#процессинг-файлов-и-информации) -- [Системный дебаггинг](#системный-дебаггинг) +- [Описание](#Описание) +- [Основы](#Основы) +- [Ежедневное использование](#Ежедневное-использование) +- [Процессинг файлов и информации](#Процессинг-файлов-и-информации) +- [Системный дебаггинг](#Системный-дебаггинг) - [В одну строчку](#В-одну-строчку) - [Сложно, но полезно](#Сложно,-но-полезно) -- [MacOS only](#macos-only) -- [Больше информации по теме](#больше-информации-по-теме) -- [Дисклеймер](#дисклеймер) +- [MacOS only](#Macos-only) +- [Больше информации по теме](#Больше-информации-по-теме) +- [Дисклеймер](#Дисклеймер) ![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 4e66f9a313e7e43baddcccfddb5736d0d749713a Mon Sep 17 00:00:00 2001 From: Oleg Berman Date: Tue, 7 Jul 2015 00:29:08 -0400 Subject: [PATCH 35/43] last achor is fixed --- README-ru.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-ru.md b/README-ru.md index f7f3c8c..ba32ef0 100644 --- a/README-ru.md +++ b/README-ru.md @@ -10,7 +10,7 @@ - [Процессинг файлов и информации](#Процессинг-файлов-и-информации) - [Системный дебаггинг](#Системный-дебаггинг) - [В одну строчку](#В-одну-строчку) -- [Сложно, но полезно](#Сложно,-но-полезно) +- [Сложно, но полезно](#Сложно-но-полезно) - [MacOS only](#Macos-only) - [Больше информации по теме](#Больше-информации-по-теме) - [Дисклеймер](#Дисклеймер) From fcbd3f667d18fce1b87f18943eb1b21755bcd4b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E6=A5=9A=E6=9D=B0?= Date: Tue, 7 Jul 2015 19:08:02 +0800 Subject: [PATCH 36/43] Update zh --- README-zh.md | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/README-zh.md b/README-zh.md index a7807ee..ed68434 100644 --- a/README-zh.md +++ b/README-zh.md @@ -11,6 +11,7 @@ - [系统调试](#系统调试) - [一行代码](#一行代码) - [冷门但有用](#冷门但有用) +- [仅限 Mac 系统](#仅限 Mac 系统) - [更多资源](#更多资源) - [免责声明](#免责声明) - [授权条款](#授权条款) @@ -31,7 +32,7 @@ 涵盖范围: - 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为 Linux 所写,但很多内容(并非所有的)同样适用于 MacOS 甚至 Cygwin。 +- 本文为 Linux 所写,除了[仅限 Mac 系统](#仅限 Mac 系统)节。其它节中的大部分内容都适用于其它 Unix 系统或 Mac 系统,甚至 Cygwin。 - 本文关注于交互式 Bash,尽管很多技巧适用于其他 shell 或 Bash 脚本。 - 本文包括了“标准的”Unix 命令和需要安装特定包的命令,只要它们足够重要。 @@ -49,7 +50,7 @@ - 学会如何使用 `man` 命令去阅读文档。学会使用 `apropos` 去查找文档。了解有些命令并不对应可执行文件,而是Bash内置的,可以使用 `help` 和 `help -d` 命令获取帮助信息。 -- 学会使用 `>` 和 `<` 来重定向输出和输入,学会使用 `|` 来重定向管道。了解标准输出 stdout 和标准错误 stderr。 +- 学会使用 `>` 和 `<` 来重定向输出和输入,学会使用 `|` 来重定向管道。明白 `>` 会覆盖了输出文件而 `>>` 是在文件未添加。了解标准输出 stdout 和标准错误 stderr。 - 学会使用通配符 `*` (或许再算上 `?` 和 `{`...`}`) 和引用以及引用中 `'` 和 `"` 的区别。 @@ -98,6 +99,8 @@ - 有关打开套接字和文件,请参阅 `lsof`。 +- 使用`alias`来创建常用命令的快捷形式。例如:`alias ll='ls -latr'`使你可以方便地执行`ls -latr`命令。 + - 在 Bash 脚本中,使用 `set -x` 去调试输出,尽可能的使用严格模式,使用 `set -e` 令脚本在发生错误时退出而不是继续运行,使用 `set -o pipefail` 严谨地对待错误(尽管问题可能很微妙)。当牵扯到很多脚本时,使用 `trap`。 - 在 Bash 脚本中,子 shell(使用括号`(...)`)是一种便捷的方式去组织参数。一个常见的例子是临时地移动工作路径,代码如下: @@ -142,13 +145,14 @@ stat -c '%A %a %n' /etc/timezone ``` -- 使用 [`percol`](https://github.com/mooz/percol) 可以交互式地从另一个命令输出中选取值。 +- 使用 [`percol`](https://github.com/mooz/percol) 或者 [`fzf`](https://github.com/junegunn/fzf) 可以交互式地从另一个命令输出中选取值。 - 使用 `fpp`([PathPicker](https://github.com/facebook/PathPicker))可以与基于另一个命令(例如 `git`)输出的文件交互。 - 将 web 服务器上当前目录下所有的文件(以及子目录)暴露给你所处网络的所有用户,使用: `python -m SimpleHTTPServer 7777` (使用端口 7777 和 Python 2)或`python -m http.server 7777` (使用端口 7777 和 Python 3)。 +- 以某种权限执行命令,使用`sudo`(root 权限)或`sudo -u`(其他用户)。使用`su`或者`sudo bash`来启动一个以对应用户权限运行的 shell。使用`su -`模拟其他用户的登录。 ## 文件及数据处理 @@ -195,7 +199,7 @@ - 使用 `shuf` 从一个文件中随机选取行。 -- 了解 `sort` 的参数。明白键的工作原理(`-t` 和 `-k`)。例如,注意到你需要 `-k1,1` 来仅按第一个域来排序,而 `-k1` 意味着按整行排序。稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用 `sort -k1,1 | sort -s -k2,2`。处理可读性数字(例如 `du -h` 的输出)的时候使用 `sort -h` 。 +- 了解 `sort` 的参数。处理数字方面,使用 `-n` 或者 `-h` 来处理可读性数字(例如 `du -h` 的输出)。明白键的工作原理(`-t` 和 `-k`)。例如,注意到你需要 `-k1,1` 来仅按第一个域来排序,而 `-k1` 意味着按整行排序。稳定排序(`sort -s`)在某些情况下很有用。例如,以第二个域为主关键字,第一个域为次关键字进行排序,你可以使用 `sort -k1,1 | sort -s -k2,2`。 - 如果你想在 Bash 命令行中写 tab 制表符,按下 **ctrl-v** **[Tab]** 或键入 `$'\t'` (后者可能更好,因为你可以复制粘贴它)。 @@ -251,9 +255,9 @@ - 关于更深层次的系统分析以及性能分析,看看 `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` +- 查看你当前使用的系统,使用 `uname` 或者 `uname -a` (Unix/kernel 信息) or `lsb_release -a` (Linux 发行版信息)。 -- 无论什么东西工作得很欢乐时试试 `dmesg` (可能是硬件或驱动问题)。 +- 无论什么东西工作得很欢乐时试试 `dmesg`(可能是硬件或驱动问题)。 ## 一行代码 @@ -436,15 +440,15 @@ 以下是*仅限于* Mac 系统的技巧 -- 用 `brew` (Homebrew)或者 `port` (MacPorts)进行包管理。这些可以用来在 Mac 系统上安装以上的大多数命令 +- 用 `brew` (Homebrew)或者 `port` (MacPorts)进行包管理。这些可以用来在 Mac 系统上安装以上的大多数命令。 -- 用 `pbcopy` 复制任何命令的输出到桌面端,用 `pbpaste` 粘贴从别处的输入 +- 用 `pbcopy` 复制任何命令的输出到桌面应用,用 `pbpaste` 粘贴输入。 -- 用 `open` 或者 `open -a /Applications/Whatever.app` 通过桌面软件打开文件 +- 用 `open` 或者 `open -a /Applications/Whatever.app` 使用桌面应用打开文件。 -- Spotlight: 用 `mdfind` 搜索文件,用 `mdls` 列出元数据(例如照片的 EXIF 信息) +- Spotlight: 用 `mdfind` 搜索文件,用 `mdls` 列出元数据(例如照片的 EXIF 信息)。 -- 注意 Mac 系统是基于 BSD UNIX 的,许多命令(例如 `ps`, `ls`, `tail`, `awk`,`sed`)都和 Linux 中有些微的不同,这些极大的被 System V-style Unix 和 GNU 工具影响。你可以通过标题为 "BSD General Commands Manual" 的 man 页面发现这些不同。在有些情况下 GNU 版本的命令也可能被安装(例如 `gawk` 和 `gsed` 对应 GNU 中的 awk 和 sed )。如果要写跨平台的 Bash 脚本,避免使用这些命令(例如,考虑 Python 或者 `perl` )或者仔细的测试。 +- 注意 Mac 系统是基于 BSD UNIX 的,许多命令(例如 `ps`, `ls`, `tail`, `awk`,`sed`)都和 Linux 中有些微的不同,这些极大的被 System V-style Unix 和 GNU 工具影响。你可以通过标题为 "BSD General Commands Manual" 的 man 页面发现这些不同。在有些情况下 GNU 版本的命令也可能被安装(例如 `gawk` 和 `gsed` 对应 GNU 中的 awk 和 sed )。如果要写跨平台的 Bash 脚本,避免使用这些命令(例如,考虑 Python 或者 `perl` )或者经过仔细的测试。 ## 更多资源 From 6c47f31c14d17c2e977486048e1624ca674b4724 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E6=A5=9A=E6=9D=B0?= Date: Tue, 7 Jul 2015 19:17:52 +0800 Subject: [PATCH 37/43] Fix errors --- README-zh.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README-zh.md b/README-zh.md index ed68434..4ac434e 100644 --- a/README-zh.md +++ b/README-zh.md @@ -11,7 +11,7 @@ - [系统调试](#系统调试) - [一行代码](#一行代码) - [冷门但有用](#冷门但有用) -- [仅限 Mac 系统](#仅限 Mac 系统) +- [仅限 Mac 系统](#仅限-Mac-系统) - [更多资源](#更多资源) - [免责声明](#免责声明) - [授权条款](#授权条款) @@ -19,7 +19,7 @@ ![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) @@ -32,7 +32,7 @@ 涵盖范围: - 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为 Linux 所写,除了[仅限 Mac 系统](#仅限 Mac 系统)节。其它节中的大部分内容都适用于其它 Unix 系统或 Mac 系统,甚至 Cygwin。 +- 本文为 Linux 所写,除了[仅限 Mac 系统](#仅限-Mac-系统)节。其它节中的大部分内容都适用于其它 Unix 系统或 Mac 系统,甚至 Cygwin。 - 本文关注于交互式 Bash,尽管很多技巧适用于其他 shell 或 Bash 脚本。 - 本文包括了“标准的”Unix 命令和需要安装特定包的命令,只要它们足够重要。 From 323df9636ddb62158566767d558c2e690caad2cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9B=BE=E6=A5=9A=E6=9D=B0?= Date: Tue, 7 Jul 2015 19:21:39 +0800 Subject: [PATCH 38/43] Fix link error --- README-zh.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-zh.md b/README-zh.md index 4ac434e..aaf237f 100644 --- a/README-zh.md +++ b/README-zh.md @@ -11,7 +11,7 @@ - [系统调试](#系统调试) - [一行代码](#一行代码) - [冷门但有用](#冷门但有用) -- [仅限 Mac 系统](#仅限-Mac-系统) +- [仅限 Mac 系统](#仅限-mac-系统) - [更多资源](#更多资源) - [免责声明](#免责声明) - [授权条款](#授权条款) @@ -32,7 +32,7 @@ 涵盖范围: - 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处。本文致力于做到覆盖面广(尽量包括一切重要的内容),具体(给出最常见的具体的例子)以及简洁(避免一些不必要的东西以及一些偏题的可以在其他地方翻阅到文献的东西)。 每个小技巧在某个特定情境下都是基本的或能够显著地节约时间。 -- 本文为 Linux 所写,除了[仅限 Mac 系统](#仅限-Mac-系统)节。其它节中的大部分内容都适用于其它 Unix 系统或 Mac 系统,甚至 Cygwin。 +- 本文为 Linux 所写,除了[仅限 Mac 系统](#仅限-mac-系统)节。其它节中的大部分内容都适用于其它 Unix 系统或 Mac 系统,甚至 Cygwin。 - 本文关注于交互式 Bash,尽管很多技巧适用于其他 shell 或 Bash 脚本。 - 本文包括了“标准的”Unix 命令和需要安装特定包的命令,只要它们足够重要。 From 46345737134fd764e9c99e4047954062c6251261 Mon Sep 17 00:00:00 2001 From: Konstantin Mikhaylov Date: Wed, 8 Jul 2015 04:41:10 +1000 Subject: [PATCH 39/43] Fixed typos in Russian translation --- README-ru.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README-ru.md b/README-ru.md index ba32ef0..e6507dd 100644 --- a/README-ru.md +++ b/README-ru.md @@ -24,7 +24,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), -начав идею там, похоже, что стоит развить ее на Gihub, где обитают люди, которые талантлевее меня и могут предлагать улучения данной подборки. Если Вы заметили ошибки (во всех вариантах перевода), пожалуйста оставьте тикет или киньте пулл-реквест (заранее изучив описание и посмотрев на уже созданнные тикеты и пулл-реквесты). +начав идею там, похоже, что стоит развить ее на Gihub, где обитают люди, которые талантливее меня и могут предлагать улучшения данной подборки. Если Вы заметили ошибки (во всех вариантах перевода), пожалуйста оставьте тикет или киньте пулл-реквест (заранее изучив описание и посмотрев на уже созданнные тикеты и пулл-реквесты). ## Описание @@ -32,12 +32,12 @@ - Данная публикация предназначена как для новичков, так и для опытных людей. Цели: *объемность* (собрать все важные аспекты использования командной строки), *практичность* (давать конкретные примеры для самых частых юзкейсов) и *краткость* (не стоит углубляться в неочевидные вещи, о которых можно почитать в другом месте). - Этот документ написан для пользователей Linux, с единственным исключеним – секцией "[MacOS only](#macos-only)". Все остальное подходит и может быть установлено под все UNIX/MacOS системы (и даже Cygwin). -- Фокусируемся на интерактивном Баше, но многие вещи так же могут быть использованы с другими шеллами; и в общем приминимы к Баш-скирптингу -- Эта инструкция включает в себя стандартные Unix комманды и те, для которых нужно устанавливать сторонние пакеты – они настолько полезны, что стоят того, чтобы их установили +- Фокусируемся на интерактивном Баше, но многие вещи так же могут быть использованы с другими шеллами; и в общем применимы к Баш-скриптингу +- Эта инструкция включает в себя стандартные Unix команды и те, для которых нужно устанавливать сторонние пакеты – они настолько полезны, что стоят того, чтобы их установили Заметки: -- Для того, чтобы руководство оставалось одностраничным, вся информация вставлена прямо сюда. Вы достаточно умные для того, чтобы самостоятельно изучить вопрос более детально в другом месте. Используйте `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (в зависимости от вашей системы управления пакетами) для установки новых програм. +- Для того, чтобы руководство оставалось одностраничным, вся информация вставлена прямо сюда. Вы достаточно умные для того, чтобы самостоятельно изучить вопрос более детально в другом месте. Используйте `apt-get`/`yum`/`dnf`/`pacman`/`pip`/`brew` (в зависимости от вашей системы управления пакетами) для установки новых программ. - На [Explainshell](http://explainshell.com/) можно найти простое и детальное объясение того, что такое команды, флаги, пайпы и т.д. @@ -47,7 +47,7 @@ - Выучите хотя бы один консольный редактор текста. Идеально Vim (`vi`), ведь у него нет конкурентов, когда вам нужно быстренько что-то подправить (даже если Вы постоянно сидите на Emacs/какой-нибудь тяжелой IDE или на каком-нибудь модном хипстерском редакторе) -- Знайте как читать документацию через `man` (для любознательных – `man man`; `man` по углам документа в скобках добавляет номер, например 1 – для обычных команд, 5 – для файлов, конвенций, 8 – для администативных команд). Ищите мануалы через `apropos`, и помните, что некоторые команды – не бинарники, а встроенные команды Баша, и помощь по ним можно получить через `help` и `help -d`. +- Знайте как читать документацию через `man` (для любознательных – `man man`; `man` по углам документа в скобках добавляет номер, например 1 – для обычных команд, 5 – для файлов, конвенций, 8 – для административных команд). Ищите мануалы через `apropos`, и помните, что некоторые команды – не бинарники, а встроенные команды Баша, и помощь по ним можно получить через `help` и `help -d`. - Узнайте о том, как перенаправлять ввод и вывод через `>` и `<` и пайпы `|`. Помните, что `>` – переписывает выходной файл, а `>>` добавляет к нему. Узнайте побольше про stdout and stderr. @@ -63,7 +63,7 @@ - Хорошо знайте регулярные выражения и разные флаги к `grep`/`egrep`. Такие флаги как `-i`, `-o`, `-A`, и `-B` стоит знать. -- Обучитесь использованию системами управления пакетами `apt-get`, `yum`, `dnf` или `pacman` (в зависимости от дистрибутива). Занйте как искать и устанавливать пакеты и обязательно имейте установленым `pip` для установки командных утилит, написаных на Python (некоторые из тех, что вы найдете ниже легче всего установить через `pip`) +- Обучитесь использованию системами управления пакетами `apt-get`, `yum`, `dnf` или `pacman` (в зависимости от дистрибутива). Знайте как искать и устанавливать пакеты и обязательно имейте установленым `pip` для установки командных утилит, написаных на Python (некоторые из тех, что вы найдете ниже легче всего установить через `pip`) ## Ежедневное использование @@ -74,11 +74,11 @@ - Если Вам нравятся шорткаты Вима сделайте `set -o vi`. -- Для того, чтобы посмотреть историю введите `history`. Так же существует множество аббривиатур, например `!$` – последний аргумент, `!!` – последняя команда, хотя эти аббривиатуры часто заменяются шорткатами **ctrl-r** и **alt-.**. +- Для того, чтобы посмотреть историю введите `history`. Так же существует множество аббривиатур, например `!$` – последний аргумент, `!!` – последняя команда, хотя эти аббревиатуры часто заменяются шорткатами **ctrl-r** и **alt-.**. - Для того, чтобы прыгнуть к последней рабочей директории – `cd -` -- Если Вы написали команду наполовину и вдруг передумали нажмите **alt-#** для того, чтобы добавить `#` к началу и отправьте комманду как комментарий. Потом вы сможете вернуться к ней через историю. +- Если Вы написали команду наполовину и вдруг передумали нажмите **alt-#** для того, чтобы добавить `#` к началу и отправьте команду как комментарий. Потом вы сможете вернуться к ней через историю. - Не забывайте использовать `xargs` (или `parallel`). Это очень мощная штука. Обратите внимание, что Вы можете контролировать количество команд на каждую строку, а так же параллельность. Если Вы не уверены, что делаете что-то правильно, начните с `xargs echo`. Еще `-I{}` – полезная штука. Примеры: ```bash @@ -156,7 +156,7 @@ ## Процессинг файлов и информации -- Для того, чтобы найти файл в текущей директории сделайте `find . -iname '*something*'`. Для того, чтобы искать файл по всей системе используйте `locate something` (но не забывайте, что `updatedb` мог еще не проидексировать недавно созданные файлы). +- Для того, чтобы найти файл в текущей директории сделайте `find . -iname '*something*'`. Для того, чтобы искать файл по всей системе используйте `locate something` (но не забывайте, что `updatedb` мог еще не проиндексировать недавно созданные файлы). - Для основого поиска по содержимому файлов (более сложному, чем `grep -r`) используйте [`ag`](https://github.com/ggreer/the_silver_searcher). @@ -226,7 +226,7 @@ - Дле веб-дебаггинга используйте `curl` и `curl -I`, или их альтернативу `wget`. Так же есть более современные альтернативы, типа [`httpie`](https://github.com/jakubroztocil/httpie). -- Чтобы получить информацию о диске/CPU/сети используйте `iostat`, `netstat`, `top` (или лучшую альтернатву `htop`) и особенно `dstat`. Хороший старт для того, чтобы понимать что происходит в системе. +- Чтобы получить информацию о диске/CPU/сети используйте `iostat`, `netstat`, `top` (или лучшую альтернативу `htop`) и особенно `dstat`. Хороший старт для того, чтобы понимать что происходит в системе. - Для более детальной информации используйте [`glances`](https://github.com/nicolargo/glances). Эта программа показывает сразу несколько разных статистик в одном окне терминале. Полезно, когда следите за сразу несколькими системами. @@ -262,7 +262,7 @@ ## В одну строчку -Давайте соберем все вместе и напишем несколько комманд: +Давайте соберем все вместе и напишем несколько команд: - Это довольно круто, что можно найти множественные пересечения файлов, соединить отсортированные файлы и посмотреть разницу в нескольких файлов через `sort`/`uniq`. Это быстрый подход и работает на файлах любого размера (включая многогигабайтные файлы). (Сортировка не ограничена памятью, но возможно вам придется добавить `-T` если `/tmp` находится на небольшом логическом диске). Еще посмотрите то что было сказано выше о `LC_ALL`. Флаг сорта `-u` option не используется ниже чтобы было понятнее: ```sh @@ -271,7 +271,7 @@ cat a b b | sort | uniq -u > c # c is set difference a - b ``` -- Используйте `grep . *` для того, чтобы посмотреть содержимое всех файлов в директории, особенно послезно когда у вас много конфигов типа `/sys`, `/proc`, `/etc`. +- Используйте `grep . *` для того, чтобы посмотреть содержимое всех файлов в директории, особенно послено когда у вас много конфигов типа `/sys`, `/proc`, `/etc`. - Получить сумму всех чисел, которые находятся в третьей колонки текстового файла. (Скорее всего, это раза в 3 быстрее и раза в 3 проще чем делать это в Питоне): @@ -283,7 +283,7 @@ ```sh find . -type f -ls ``` -Это почти как рекурсивная `ls -l, но более читабельно чем `ls -lR`: +Это почти как рекурсивная `ls -l`, но более читабельно чем `ls -lR`: - Используйте `xargs` (или `parallel`). Это очень мощная штука. Обратите внимание, что Вы можете контролировать количество команд на каждую строку, а так же параллельность. Если Вы не уверены, что делаете что-то правильно, начните с `xargs echo`. Еще `-I{}` – полезная штука. Примеры: ```sh @@ -452,7 +452,7 @@ - Spotlight: Ищите файлы в консоле через `mdfind` и смотрите метадату (например EXIF информацию фотографий) через `mdls`. -- Не забывайте, что MacOS основан на BSD Uni и многие команды (например `ps`, `ls`, `tail`, `awk`, `sed`) имеют некоторые небольшие различия с линуксовыми. Это обусловлено влянием `UNIX System V` и `GNU Tools`. Разницу можно заметить увидив заголовок "BSD General Commands Manual." к манам програм. В некоторых случаях, на Мак можно поставить GNU-версии программ, например `gawk` и `gsed`. Когда пишите кроссплатформенные Bash-скрипты, старайтесь избегать команды, которые могут различаться (например, лучше используйте Python или `perl`), или тщательно все тестируйте. +- Не забывайте, что MacOS основан на BSD Uni и многие команды (например `ps`, `ls`, `tail`, `awk`, `sed`) имеют некоторые небольшие различия с линуксовыми. Это обусловлено влянием `UNIX System V` и `GNU Tools`. Разницу можно заметить увидив заголовок "BSD General Commands Manual." к манам программ. В некоторых случаях, на Мак можно поставить GNU-версии программ, например `gawk` и `gsed`. Когда пишите кроссплатформенные Bash-скрипты, старайтесь избегать команды, которые могут различаться (например, лучше используйте Python или `perl`), или тщательно все тестируйте. ## Больше информации по теме From 4da306c54be5c908fb6ddad7f3894fdec9c2ba93 Mon Sep 17 00:00:00 2001 From: Alex Vergara Gil Date: Tue, 7 Jul 2015 14:47:36 -0400 Subject: [PATCH 40/43] Grammar and orthography checks --- README-es.md | 110 +++++++++++++++++++++++++-------------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/README-es.md b/README-es.md index e6ec203..96ea809 100644 --- a/README-es.md +++ b/README-es.md @@ -7,7 +7,7 @@ - [Meta](#meta) - [Fundamentos](#basics) - [De uso diario](#everyday-use) -- [Procesamieto de archivos y datos](#processing-files-and-data) +- [Procesamiento de archivos y datos](#processing-files-and-data) - [Depuración del sistema](#system-debugging) - [One-liners](#one-liners) - [Obscuro pero útil](#obscure-but-useful) @@ -18,70 +18,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) -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. +La fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora su flexibilidad y productividad como ingeniero en formas obvia y sutil. Esta es una selección de notas y consejos al usar el terminal que encuentro útil cuando trabajo en Linux. Algunos consejos son elementales y algunos bastante específicos, sofisticados u oscuros. Esta página no es larga, pero si usa y recuerda todos los puntos aquí mostrados, ustedes sabrán un montón. -Gran parte esta +Gran parte está en [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.) +pero debido al interés mostrado ahí, parece que vale la pena usar Github, donde existen personas con mayor talento que fácilmente pueden sugerir mejoras. Si ve 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. 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, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros Unices o 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. +- Esta guía es tanto para el principiante como para 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 fácilmente en otro lugar). Cada consejo es esencial en alguna situación o significativamente ahorra tiempo comparada con otras alternativas. +- Esta escrito para Linux, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros UNIX o MacOS (o incluso Cygwin). +- Se enfoca 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, así como aquellos que requieren la instalación especial de un paquete -- siempre que sea suficientemente importante para ameritar su inclusión. Notas: -- 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. +- Para mantener esto en una página, el contenido esta incluido implícitamente por referencia. Usted es suficientemente inteligente para ver profundamente los detalles en otros lugares, cuando conoces la idea o comando 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, opciones, pipes, etc. ## Fundamentos -- 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). +- Aprenda conocimientos básicos de Bash, de hecho, escriba `man bash` y al menos échele un vistazo a toda 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 (conocer *solo* zsh, fish, etc., aunque resulte tentador en tu propia laptop, los restringe en muchas situaciones, tales como el uso de servidores existentes). -- 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). +- Aprenda bien al menos un editor de texto, idealmente Vim (`vi`), como no hay realmente una competencia para la edición aleatoria en un terminal (incluso si usa Emacs, un gran IDE, o un editor alternativo (hipster) moderno la mayor parte del tiempo). -- 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`. +- Conozca como leer la documentación 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, pero son Bash builtins, y que puede obtener ayuda sobre ellos con `help` y `help -d`. -- Aprenda sobre redirección de salida y entrada `>` y `<` and pipes utilizando `|`. Conozca `>` sobre escribe el archivo de salida y `>>` añade. Aprenda sobre stdout y stderr. +- Aprenda sobre redirección de salida y entrada (`>` y `<`); pipes utilizando `|`. Conozca que `>` sobrescribe el archivo de salida y `>>` añade. Aprenda sobre stdout y stderr. -- 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.) +- Aprenda sobre expansión de archivos glob con `*` (y tal vez `?` y `{`...`}`) y quoting y la diferencia entre doble `"` y simple `'` quotes. (Ver más en expansión de variables más abajo.) -- Familiarizate con administración de trabajo en Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. +- Familiarízate con la administración de trabajo en Bash: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc. -- Conoce `ssh`, y lo básico de authenticacion sin password, via `ssh-agent`, `ssh-add`, etc. +- Conoce `ssh` y lo básico de autenticación sin contraseña, vía `ssh-agent`, `ssh-add`, etc. -- Adminisración de archivos básica: `ls` y `ls -l` (en particular, aprenda el significado de cada columna en `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 -hk *`). Para administración de filesystem, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. +- Administración de archivos básica: `ls` y `ls -l` (en particular, aprenda el significado de cada columna en `ls -l`), `less`, `head`, `tail` y `tail -f` (o incluso mejor, `less +F`), `ln` y `ln -s` (aprenda las diferencias y ventajas entre enlaces hard y soft), `chown`, `chmod`, `du` (para un resumen rápido del uso del disco: `du -hk *`). Para administración de archivos de sistema, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. -- Administración de redes básico: `ip` o `ifconfig`, `dig`. +- Administración básica de redes: `ip` o `ifconfig`, `dig`. -- Conozca expresiones regulares bien, y varias banderas (flags) para `grep`/`egrep`. El `-i`, `-o`, `-A`, y `-B` son opciones dignas de ser conocidas. +- Conozca bien las expresiones regulares y varias opciones (flags) para `grep`/`egrep`. Las opciones `-i`, `-o`, `-A`, y `-B` son dignas de ser recordadas. -- 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`). +- Aprenda el uso de `apt-get`, `yum`, `dnf` o `pacman` (dependiendo de la distribución "distro") para buscar e instalar paquetes. Y asegúrate que tienes `pip` para instalar la herramienta de línea de comando basada en Python (un poco más abajo esta explicado como instalar vía `pip`). ## De uso diario -- En Bash, se usa **Tab** para completar los argumentos y **ctrl-r** para buscar, a través, del historial de comandos. +- En Bash, se usa **Tab** para completar los argumentos y **ctrl-r** para buscar, a través del historial de comandos. -- 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. +- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar todo el camino desde 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-.** realiza un ciclo a través de los comandos previos, y **alt-*** expande un glob. -- Alternativamente, si tu amas los atajos de teclado vi-style, usa `set -o vi`. +- Alternativamente, si amas los atajos de teclado vi-style, usa `set -o vi`. - 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-.**. - Para volver al diretorio de trabajo previo: `cd -` -- 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. +- 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 history. -- `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: +- Se usa `xargs` (or `parallel`). Esto es muy poderoso. Nota: puedes controlar muchos items ejecutados por línea (`-L`), tamabién es conocido como paralelismo (`-P`). Si no estas seguro, este puede ser el camino correcto, 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 @@ -101,16 +101,16 @@ Notas: - Usar `alias` para crear atajos para comandos comúnmente usados. Por ejemplo, `alias ll="las -latr"` crea un nuevo alias `ll` -- 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`. +- En guiones Bash, 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 guiones más complejos, también se puede utilizar `trap`. -- 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. +- En guiones Bash, subshells (escritos con parentesís) son maneras convenientes para agrupar los comandos. Un ejemplo común es para moverse temporalmente hacia un directorio diferente del de trabajo, Ej. ```bash # do something in current dir (cd /some/other/dir && other-command) # continue in original dir ``` -- 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`. +- En Bash, considere que hay muchas formas de expansión de variables. Verificar la existencia de una variable: `${name:?error message}`. Por ejemplo, si un guión 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`. - La salida de un comando puede ser tratado como un archivo, via `<(some command)`. Por ejemplo, compare local `/etc/hosts` con uno remoto: ```sh @@ -119,11 +119,11 @@ Notas: - Conocer acerca "here documents" en Bash, así también `cat <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 `logfile 2>&1`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estandar vinculada al terminal en el que te encuentras y también como buena practica puedes agregar ` foo: rename 's/\.bak$//' *.bak @@ -202,7 +202,7 @@ Notas: - Conozca las opciones de `sort`. Para números, use `-n`, o `-h` para manipulación de números humanamente leibles (Ej. desde `du -h`). 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. Orden estable (`sort -s`) puede ser útil. Por ejemplo, para organizar el primer por el campo 2, entonces secundariamente hacerlo por el campo 1, Puedes usar `sort -k1,1 | sort -s -k2,2`. -- 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). +- Si necesitas siempre 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). - 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. @@ -232,7 +232,7 @@ Notas: - 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". -- 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. +- El sistema de depuració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. - Usar `mtr` como un mejor traceroute, para identificar los problemas en la red. @@ -246,7 +246,7 @@ Notas: - 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`). -- Conozca acerca `ldd` para verificar librerias compartidas etc. +- Conozca acerca `ldd` para verificar librerías compartidas etc. - Conozca como conectarse a un proceso en ejecución con `gdb` y obtener su traza de pilas. @@ -254,7 +254,7 @@ Notas: - 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. -- 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). +- Para sistemas y análisis 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). - Confirmar que OS te encuentras con `uname` o `uname -a` (información general Unix/kernel) o `lsb_release -a` (Linux distro info). @@ -308,9 +308,9 @@ Algunos ejemplos de comandos reunidos: ``` -## Obscuro pero útil +## Oscuro pero útil -- `expr`: ejecuta operaciones aritmeticas o booleanas o evalua expresiones regulares +- `expr`: ejecuta operaciones aritméticas o booleanas o evalúa expresiones regulares - `m4`: macro procesador sencillo @@ -346,9 +346,9 @@ Algunos ejemplos de comandos reunidos: - `gpg`: cifrado y firmas digitales -- `toe`: tabla de información de terminos +- `toe`: tabla de información de términos -- `nc`: deputación del entorno de red y transferencia de datos +- `nc`: depuración del entorno de red y transferencia de datos - `socat`: socket relay y redireccionador de puerto tcp (similar a `netcat`) @@ -384,17 +384,17 @@ Algunos ejemplos de comandos reunidos: - `units`: unidades de conversión y calculaciones; convierte furlongs por fortnight para twips por blink (ver también `/usr/share/units/definitions.units`) -- `7z`: conpresión de archivos de alto nivel +- `7z`: compresión de archivos de alto nivel -- `ldd`: información de libreria dinamica +- `ldd`: información de librería dinámica - `nm`: archivo de objeto de simbolos -- `ab`: benchmarking de servdores web +- `ab`: benchmarking de servidores web - `strace`: depuración de llamadas del sistema -- `mtr`: mejor traceroute para la deputación de la red +- `mtr`: mejor traceroute para la depuración de la red - `cssh`: shell concurrent visual @@ -408,25 +408,25 @@ Algunos ejemplos de comandos reunidos: - `lsof`: descriptor de archivo de procesos y información de socket -- `dstat`: sistema de estadisticas útil +- `dstat`: sistema de estadísticas útil - [`glances`](https://github.com/nicolargo/glances):vistazo de multi-subsistemas, de alto nivel - `iostat`: estadísticas del CPU y uso del disco -- `htop`: version mejorada de top +- `htop`: versión mejorada de top - `last`: historial de login -- `w`: quien esta authenticado? +- `w`: quien esta autenticado? - `id`: información de identidad de usuario/grupo -- `sar`: sistema de estadisticas historico +- `sar`: sistema de estadísticas histórico - `iftop` o `nethogs`: utilización de la red por un socket o process -- `ss`: estadisticas de socket +- `ss`: estadísticas de socket - `dmesg`: arranque y sistema de mensajes de error @@ -449,11 +449,11 @@ Estos son puntos relevantes *solo* en MacOS. - Copiar la salida de cualquier comando para una aplicación desktop con `pbcopy` y pegar desde una entrada con `pbpaste`. -- Para abrir un archivo con una applicación desktop, usar `open` o `open -a /Applications/Whatever.app`. +- Para abrir un archivo con una aplicación desktop, usar `open` o `open -a /Applications/Whatever.app`. - Spotlight: Busca archivos con `mdfind` y listar metadata (como información de foto EXIF) con `mdls`. -- Tenga encuenta que MacOS esta basado en BSD Unix, y cualquier commando (por ejemplo `ps`, `ls`, `tail`, `awk`, `sed`) tiene variaciones discretas variaciones por cada Linux, que esta en gran parte influenciado por el sistema Unix V-style y herramientas GNU. Puedes frecuentemente decirme la diferencia por señalar unas páginas man que tienen el encabezado "BSD General Commands Manual." En algunos casos versiones GNU pueden ser instalados, también (tales como `gawk` y `gsed` para awk y sed del GNU). Si escribe cross-platform scripts Bash, evita tales comandos (por ejemplo, considerando Python o `perl`) o probar con mucho cuidado. +- Tenga encuenta que MacOS esta basado en BSD Unix, y cualquier comando (por ejemplo `ps`, `ls`, `tail`, `awk`, `sed`) tiene variaciones discretas variaciones por cada Linux, que esta en gran parte influenciado por el sistema Unix V-style y herramientas GNU. Puedes frecuentemente decirme la diferencia por señalar unas páginas man que tienen el encabezado "BSD General Commands Manual." En algunos casos versiones GNU pueden ser instalados, también (tales como `gawk` y `gsed` para awk y sed del GNU). Si escribe cross-platform scripts Bash, evita tales comandos (por ejemplo, considerando Python o `perl`) o probar con mucho cuidado. ## Más recursos From ab1efba06dd074a90aa7fb4549f902df3d194a31 Mon Sep 17 00:00:00 2001 From: Alex Vergara Gil Date: Tue, 7 Jul 2015 15:54:36 -0400 Subject: [PATCH 41/43] Some modifications accepting suggestions --- README-es.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README-es.md b/README-es.md index 96ea809..f05b2db 100644 --- a/README-es.md +++ b/README-es.md @@ -18,7 +18,7 @@ ![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '`\w+`' | tr -d '`' | cowsay -W50](cowsay.png) -La fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora su flexibilidad y productividad como ingeniero en formas obvia y sutil. Esta es una selección de notas y consejos al usar el terminal que encuentro útil cuando trabajo en Linux. Algunos consejos son elementales y algunos bastante específicos, sofisticados u oscuros. Esta página no es larga, pero si usa y recuerda todos los puntos aquí mostrados, ustedes sabrán un montón. +La fluidez en el terminal es una destreza a menudo abandonada y considerada arcaica, pero esta mejora su flexibilidad y productividad como ingeniero en formas obvia y sutil. Esta es una selección de notas y consejos al usar el terminal que encontré útiles al trabajar en Linux. Algunos consejos son elementales y algunos bastante específicos, sofisticados u oscuros. Esta página no es larga, pero si usa y recuerda todos los puntos aquí mostrados, ustedes sabrán un montón. Gran parte está en [originally](http://www.quora.com/What-are-some-lesser-known-but-useful-Unix-commands) @@ -50,7 +50,7 @@ Notas: - Conozca como leer la documentación 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, pero son Bash builtins, y que puede obtener ayuda sobre ellos con `help` y `help -d`. -- Aprenda sobre redirección de salida y entrada (`>` y `<`); pipes utilizando `|`. Conozca que `>` sobrescribe el archivo de salida y `>>` añade. Aprenda sobre stdout y stderr. +- Aprenda sobre redirección de salida >, entrada < y pipes utilizando `|`. Conozca que `>` sobrescribe el archivo de salida y `>>` añade. Aprenda sobre stdout y stderr. - Aprenda sobre expansión de archivos glob con `*` (y tal vez `?` y `{`...`}`) y quoting y la diferencia entre doble `"` y simple `'` quotes. (Ver más en expansión de variables más abajo.) From 9c56995dd2df9bc3d7fef8999e282b66f3345507 Mon Sep 17 00:00:00 2001 From: Alex Vergara Gil Date: Tue, 7 Jul 2015 16:53:25 -0400 Subject: [PATCH 42/43] More suggested changes --- README-es.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README-es.md b/README-es.md index f05b2db..c3334d3 100644 --- a/README-es.md +++ b/README-es.md @@ -24,7 +24,7 @@ Gran parte está en [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 existen personas con mayor talento que fácilmente pueden sugerir mejoras. Si ve 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.) +pero debido al interés mostrado, parece que vale la pena usar Github, donde existen personas más talentosas, que fácilmente pueden sugerir mejoras. Si ve 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 @@ -71,7 +71,7 @@ Notas: - En Bash, se usa **Tab** para completar los argumentos y **ctrl-r** para buscar, a través del historial de comandos. -- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar todo el camino desde 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-.** realiza un ciclo a través de los comandos previos, y **alt-*** expande un glob. +- En Bash, se usa **ctrl-w** para borrar la última palabra, y **ctrl-u** para borrar 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-.** realiza un ciclo a través de los comandos previos, y **alt-*** expande un glob. - Alternativamente, si amas los atajos de teclado vi-style, usa `set -o vi`. @@ -181,9 +181,9 @@ Notas: - Conocer acerca `tee` para copiar desde el stdin hacia un archivo y también hacia el stdout, así `ls -al | tee file.txt`. -- Conocer que `locale` afecta muchas herramientas de línea de comando en forma delicada, incluyendo el orden del ordenamiento (compaginación) y rendimiento. La mayoria de las instalaciones de Linux configuran `LANG` u otras variables de localización para la configuración local como US English. Pero esté alerta, el ordenamiento puede cambiar si 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`. +- Conocer que `locale` afecta muchas herramientas de línea de comando en forma delicada, incluyendo el orden del ordenamiento (compaginación) y rendimiento. La mayoría de las instalaciones de Linux configuran `LANG` u otras variables de localización para la configuración local como US English. Pero esté alerta, el ordenamiento puede cambiar si cambia la localización. Y también las rutinas i18n pueden hacer que `sort` u otros comandos se ejecuten **muchas veces** más 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 tradicional basado en byte, usando `export LC_ALL=C`. -- Conozca `awk` y `sed` para mapeo de datos sencillos. 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. +- Conozca aspectos básicos de `awk` y `sed` para manejo de datos. 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. - Para remplazar todas las ocurrencias de un string en su lugar, en uno o más archivos: ```sh @@ -198,7 +198,7 @@ Notas: repren --full --preserve-case --from foo --to bar . ``` -- Usar `shuf` para mezclar o seleccionar líneas aleatoreas desde un archivo. +- Usar `shuf` para mezclar o seleccionar líneas aleatorias desde un archivo. - Conozca las opciones de `sort`. Para números, use `-n`, o `-h` para manipulación de números humanamente leibles (Ej. desde `du -h`). 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. Orden estable (`sort -s`) puede ser útil. Por ejemplo, para organizar el primer por el campo 2, entonces secundariamente hacerlo por el campo 1, Puedes usar `sort -k1,1 | sort -s -k2,2`. @@ -212,7 +212,7 @@ Notas: - Para diffs binaria (delta compression), usar `xdelta3`. -- 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): +- Para convertir 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 ``` @@ -265,7 +265,7 @@ Notas: Algunos ejemplos de comandos reunidos: -- 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). +- Este es notablemente ú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 únicos. Esto es rápido, y trabaja con archivos de tamaño arbitrario, hasta varios gigabytes. (Sort no esta limitado por la memoria, aunque quizás 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 @@ -296,7 +296,7 @@ Algunos ejemplos de comandos reunidos: cat access.log | egrep -o 'acct_id=[0-9]+' | cut -d= -f2 | sort | uniq -c | sort -rn ``` -- Ejecta esta función para obtener un consejo aleatoreo desde este documento (analiza el Markdown y extrae un elemento): +- Ejecuta esta función para obtener un consejo aleatorio 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 | @@ -380,7 +380,7 @@ Algunos ejemplos de comandos reunidos: - `split` y `csplit`: división de archivos -- `sponge`: lee todas las entradas antes de escribirlo, útil para lectura desde useful for reading y luego la escritura hacia el mismo archivo, Ej., `grep -v something some-file | sponge some-file` +- `sponge`: lee todas las entradas antes de escribirlo, útil para vista previa y posterior escritura hacia el mismo archivo, Ej., `grep -v something some-file | sponge some-file` - `units`: unidades de conversión y calculaciones; convierte furlongs por fortnight para twips por blink (ver también `/usr/share/units/definitions.units`) From e4510188281424d278a1a1d83c96fd8d9ffea0bb Mon Sep 17 00:00:00 2001 From: Alex Vergara Gil Date: Tue, 7 Jul 2015 17:18:44 -0400 Subject: [PATCH 43/43] More changes in the revision --- README-es.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/README-es.md b/README-es.md index c3334d3..be5af62 100644 --- a/README-es.md +++ b/README-es.md @@ -32,7 +32,7 @@ pero debido al interés mostrado, parece que vale la pena usar Github, donde exi Alcance: - Esta guía es tanto para el principiante como para 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 fácilmente en otro lugar). Cada consejo es esencial en alguna situación o significativamente ahorra tiempo comparada con otras alternativas. -- Esta escrito para Linux, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros UNIX o MacOS (o incluso Cygwin). +- Esta escrito para Linux, con excepción de la sección "[Solo para MacOS](#macos-only)". Muchos de los otros puntos aplican o pueden ser instalados en otros Unices o MacOS (o incluso Cygwin). - Se enfoca 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, así como aquellos que requieren la instalación especial de un paquete -- siempre que sea suficientemente importante para ameritar su inclusión. @@ -79,7 +79,7 @@ Notas: - Para volver al diretorio de trabajo previo: `cd -` -- 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 history. +- Si estas a mitad de camino de escritura de un comando pero cambias de opinión, presiona **alt-#** para agregar un `#` al principio y lo agrega como comentario (o usar **ctrl-a**, **#**, **enter**). Para que puedas entonces regresar a este luego vía comando `history`. - Se usa `xargs` (or `parallel`). Esto es muy poderoso. Nota: puedes controlar muchos items ejecutados por línea (`-L`), tamabién es conocido como paralelismo (`-P`). Si no estas seguro, este puede ser el camino correcto, usa `xargs echo` primero. También, `-I{}` es comodo. Ejemplos: ```bash @@ -101,33 +101,33 @@ Notas: - Usar `alias` para crear atajos para comandos comúnmente usados. Por ejemplo, `alias ll="las -latr"` crea un nuevo alias `ll` -- En guiones Bash, 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 guiones más complejos, también se puede utilizar `trap`. +- En scripts Bash, 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 (aunque este tema es un poco delicado). Para scripts más complejos, también se puede utilizar `trap`. -- En guiones Bash, subshells (escritos con parentesís) son maneras convenientes para agrupar los comandos. Un ejemplo común es para moverse temporalmente hacia un directorio diferente del de trabajo, Ej. +- En scripts Bash, subshells (escritos con parentesís) son maneras convenientes para agrupar los comandos. Un ejemplo común es para moverse temporalmente hacia un directorio diferente del de trabajo, Ej. ```bash # do something in current dir (cd /some/other/dir && other-command) # continue in original dir ``` -- En Bash, considere que hay muchas formas de expansión de variables. Verificar la existencia de una variable: `${name:?error message}`. Por ejemplo, si un guión 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`. +- En Bash, considere que hay muchas formas de expansión de variables. 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`. -- La salida de un comando puede ser tratado como un archivo, via `<(some command)`. Por ejemplo, compare local `/etc/hosts` con uno remoto: +- La salida de un comando puede ser tratado como un archivo, vía `<(some command)`. Por ejemplo, compare local `/etc/hosts` con uno remoto: ```sh diff /etc/hosts <(ssh somehost cat /etc/hosts) ``` - Conocer acerca "here documents" en Bash, así también `cat <logfile 2>&1`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estandar vinculada al terminal en el que te encuentras y también como buena practica puedes agregar `logfile 2>&1`. Frecuentemente, para garantizar que un comando no haya dejado abierto un archivo para controlar la entrada estándar vinculada al terminal en el que te encuentras y también como buena practica puedes agregar `` 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. +- El sistema de depuració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 colección de basura generacional, la cual puede ser altamente informativa) serán descargados al stderr/logs. - Usar `mtr` como un mejor traceroute, para identificar los problemas en la red. @@ -240,7 +240,7 @@ Notas: - Para encontrar cual socket o proceso esta utilizando el ancho de banda, prueba `iftop` o `nethogs`. -- 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`. +- La herramienta `ab` (viene con Apache) es útil para una verificación rápida y sucia del rendimiento del servidor web. Para pruebas de carga más complejas, prueba `siege`. - Para depuración de redes más serias, `wireshark`, `tshark`, o `ngrep`. @@ -250,7 +250,7 @@ Notas: - Conozca como conectarse a un proceso en ejecución con `gdb` y obtener su traza de pilas. -- 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`. +- Usar `/proc`. Este es extraordinariamente útil algunas veces cuando hay problemas de depuración en vivo. Ejemplos: `/proc/cpuinfo`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps`. - 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. @@ -258,14 +258,14 @@ Notas: - Confirmar que OS te encuentras con `uname` o `uname -a` (información general Unix/kernel) o `lsb_release -a` (Linux distro info). -- Usar `dmesg` siempre que algo actue comico (esto podría ser problemas con el hardware o driver). +- Usar `dmesg` siempre que algo actúe raro (esto podría ser problemas con el hardware o driver). ## One-liners Algunos ejemplos de comandos reunidos: -- Este es notablemente ú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 únicos. Esto es rápido, y trabaja con archivos de tamaño arbitrario, hasta varios gigabytes. (Sort no esta limitado por la memoria, aunque quizás 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). +- Este es notablemente útil en ocasiones que hay que realizar intersección, unión, y diferencia de archivos de texto vía `sort`/`uniq`. Considere `a` y `b` como archivos de texto que son únicos. Esto es rápido, y trabaja con archivos de tamaño arbitrario, hasta varios gigabytes. (Sort no esta limitado por la memoria, aunque quizás 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 @@ -275,7 +275,7 @@ Algunos ejemplos de comandos reunidos: - 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`. -- 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): +- Sumar todos os números en la tercera columna de un archivo de texto (esto es probablemente 3X más rápido 3X menor código que el equivalente en Python): ```sh awk '{ x += $3 } END { print x }' myfile ``` @@ -322,7 +322,7 @@ Algunos ejemplos de comandos reunidos: - `printenv`: imprime las variables del ambiente (útil en depuración y scripts) -- `look`: buscar palabras en English (o líneas en un archivo) comanzando con un string +- `look`: buscar palabras en English (o líneas en un archivo) comenzando con un string - `cut`, `paste` y `join`: manipulación de datos