the-art-of-command-line README

README проекта с github.com/jlevy/the-art-of-command-line. Одним файлом markdown: README.md.

🌍 Čeština ∙ Deutsch ∙ Ελληνικά ∙ English ∙ Español ∙ Français ∙ Indonesia ∙ Italiano ∙ 日本語 ∙ 한국어 ∙ polski ∙ Português ∙ Română ∙ Русский ∙ Slovenščina ∙ Українська ∙ 简体中文 ∙ 繁體中文

The Art of Command Line

Note: I'm planning to revise this and looking for a new co-author to help with expanding this into a more comprehensive guide. While it's very popular, it could be broader and a bit deeper. If you like to write and are close to being an expert on this material and willing to consider helping, please drop me a note at josh (0x40) holloway.com. –jlevy, Holloway. Thank you!

![curl -s 'https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md' | egrep -o '\w+' | tr -d '`' | cowsay -W50](cowsay.png)

Fluency on the command line is a skill often neglected or considered arcane, but it improves your flexibility and productivity as an engineer in both obvious and subtle ways. This is a selection of notes and tips on using the command-line that we've found useful when working on Linux. Some tips are elementary, and some are fairly specific, sophisticated, or obscure. This page is not long, but if you can use and recall all the items here, you know a lot.

This work is the result of many authors and translators. Some of this originally appeared on Quora, but it has since moved to GitHub, where people more talented than the original author have made numerous improvements. Please submit a question if you have a question related to the command line. Please contribute if you see an error or something that could be better!

Meta

Scope:

Notes:

Basics

Everyday use

      find . -name '*.py' | xargs grep some_function
      cat hosts | xargs -I{} ssh root@{} hostname
      set -euo pipefail
      trap "echo 'error: Script failed: see failed command above'" ERR
      # do something in current dir
      (cd /some/other/dir && other-command)
      # continue in original dir
      diff /etc/hosts <(ssh somehost cat /etc/hosts)
{
      # Your code here
}
cat <<EOF
input
on multiple lines
EOF
      TCPKeepAlive=yes
      ServerAliveInterval=15
      ServerAliveCountMax=6
      Compression=yes
      ControlMaster auto
      ControlPath /tmp/%r@%h:%p
      ControlPersist yes
      stat -c '%A %a %n' /etc/timezone
>>> 2+3
5

Processing files and data

      perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
      # Full rename of filenames, directories, and contents foo -> bar:
      repren --full --preserve-case --from foo --to bar .
      # Recover backup files whatever.bak -> whatever:
      repren --renames --from '(.*)\.bak' --to '\1' *.bak
      # Same as above, using rename, if available:
      rename 's/\.bak$//' *.bak
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
      # Displays hex codes or actual names of characters (useful for debugging):
      uconv -f utf-8 -t utf-8 -x '::Any-Hex;' < input.txt
      uconv -f utf-8 -t utf-8 -x '::Any-Name;' < input.txt
      # Lowercase and removes all accents (by expanding and dropping them):
      uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC;' < input.txt > output.txt
   getfacl -R /some/path > permissions.txt
   setfacl --restore=permissions.txt

System debugging

One-liners

A few examples of piecing together commands:

      sort a b | uniq > c   # c is a union b
      sort a b | uniq -d > c   # c is a intersect b
      sort a b b | uniq -u > c   # c is set difference a - b
      diff <(jq --sort-keys . < file1.json) <(jq --sort-keys . < file2.json) | colordiff | less -R
      awk '{ x += $3 } END { print x }' myfile
      find . -type f -ls
      egrep -o 'acct_id=[0-9]+' access.log | cut -d= -f2 | sort | uniq -c | sort -rn
      function taocl() {
        curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
          sed '/cowsay[.]png/d' |
          pandoc -f markdown -t html |
          xmlstarlet fo --html --dropdtd |
          xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
          xmlstarlet unesc | fmt -80 | iconv -t US
      }

Obscure but useful

macOS only

These are items relevant only on macOS.

Windows only

These items are relevant only on Windows.

Ways to obtain Unix tools under Windows

Useful Windows command-line tools

Cygwin tips and tricks

More resources

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

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

the-art-of-command-line (jlevy/the-art-of-command-line)

Ищем в базе…

Что это такое?Одностраничное руководство с основными советами, приёмами и заметками по работе с Bash в Linux и других Unix-подобных системах: от основ до продвинутого написания скриптов и отладки.
Это руководство, которое нужно читать от начала до конца, или скорее справочник?Оно разбито на разделы («Основы», «Повседневное использование», «Обработка файлов и данных», «Отладка системы», «Однострочники», «Малоизвестное, но полезное», «Только macOS», «Только Windows»), поэтому его можно прочитать целиком или сразу перейти к нужной теме, а команды, название которых уже известно, искать в других источниках.
С чего стоит начать новичку?Начните с раздела «Основы»: прочитайте страницу man bash целиком, выберите текстовый редактор (nano для простоты, Vim или Emacs для опытных пользователей) и научитесь находить документацию с помощью man и apropos.
Нужны ли особые инструменты, чтобы повторять всё за автором, или достаточно только терминала?Достаточно стандартного терминала Unix/Linux с Bash. В некоторых советах упоминаются дополнительные инструменты, которые устанавливаются через apt, yum, dnf, pacman, pip или brew.
Всё ли здесь относится и к macOS, и к Windows?Нет. Руководство написано по умолчанию для Linux, а отдельные специальные разделы есть только для того, что касается macOS и Windows. Многие другие советы тоже работают в других системах, но это не гарантировано.
Это для полных новичков или для опытных системных администраторов?Для тех и других. Руководство стремится к широте охвата и краткости, поэтому оно полезно как тем, кто только начинает работать с командной оболочкой, так и тем, у кого уже есть солидный опыт.
На какую оболочку ориентировано руководство?В центре внимания интерактивный Bash, однако многие советы подходят и для других оболочек, а также для написания скриптов на Bash в целом.
Есть ли в нём рекомендации по написанию скриптов, а не только по интерактивной работе?Да, там описаны привычки при написании скриптов на Bash, например использование set -e, set -u, set -o pipefail и trap для обработки ошибок, а также подводные камни при подстановке переменных и работе с кавычками.
Есть ли инструмент, который помогает разобраться в незнакомых командах?Да, руководство рекомендует Explainshell, чтобы получить разбор того, что делают опции команды и её конвейеры, а также curl cheat.sh/command для быстрых шпаргалок.
Есть ли это руководство на других языках?Да, оно переведено на многие языки, включая чешский, немецкий, греческий, испанский, французский, японский, корейский, польский, португальский, румынский, русский, украинский, а также упрощённый и традиционный китайский.
Какие есть похожие проекты?Linux-, awesome-dotfiles, awesome-bash, awesome-zsh-plugins, nvm, awesome-adb, fq-book, tmux
Автор
jlevy
Размер
2.7 MB
Звёзды
162.8K
Обновлён
КоммитJul 12
Возраст
11 г
Коммиты · 90 дней