- 20 советов для линукс-гиков
- 1. Список не ваших процессов
- 2. Замена текста в файлах
- 3. Исправить консоль
- 4. Создать keywords в Mozill’е
- 5. Запуск множественных X-сессий
- 6. Ускорение серфинга
- 7. Легкое резервное копирование
- 8. Поддерживать ваши часы в актуальном состоянии
- 9. Поиск самых больших файлов
- 10. Горячие клавиши Nautilus’а
- 11. Оптимизация баз данных
- 12. Быстрые письма
- 13. Распараллеливание сборки
- 14. Увеличение время работы батареи
- 15. Управление скоростью беспроводного подключения
- 16. Список откртых портов
- 17. Увеличение скорости работы жестких дисков
- 18. Удаленный доступ к вашим программ.
- 20. Диаграмма взаимосвязи пакетов
- 21. Принудительное отключение занятых устройств
- 22. Конвертирование кодировок текстовых файлов
- 23. Поиск измененных сегодня файлов
- 21 Super Handy Linux Command Tips and Tricks That Will Save you a lot of Time and Increase Your Productivity
- Cool Linux terminal tricks to save time and increase productivity
- 0. Using tab for autocompletion
- 1. Switch back to the last working directory
- 2. Go back to home directory
- 3. List the contents of a directory
- 4. Running multiple commands in one single command
- 5. Running multiple commands in one single command only if the previous command was successful
- 6. Easily search and use the commands that you had used in the past
- 7. Unfreeze your Linux terminal from accidental Ctrl+S
- 8. Move to beginning or end of line
- 9. Delete entire line from cursor position
- 10. Reading a log file in real time
- 11. Reading compressed logs without extracting
- 12. Use less to read files
- 13. Reuse the last item from the previous command with !$
- 14. Reuse the previous command in present command with !!
- 15. Using alias to fix typos
- 16. Copy Paste in Linux terminal
- 17. Kill a running command/process
- 18. Using yes command for commands or scripts that need interactive response
- 19. Empty a file without deleting it
- 20. Find if there are files containing a particular text
- 21. Using help with any command
- Your favorite Linux command line tricks?
20 советов для линукс-гиков
Что отличает обычного пользователя Линукса от профессионала? Ответ прост: это — годы, проведенные за изучением хитростей и приемов, которые позволяют решать не быстрые задачи в одно мгновение. Если вы хотите увеличить скорость работы без долгого набивания шишек в консоли, подобрано 20 легких для изучения приемов. Они помогут сделать вашу работу эффективной и выжать максимум возможностей из вашего компьютера.
1. Список не ваших процессов
Представьте ситуацию: вы уже приготовились к игре в Counter-Strike с вашими коллегами в пятничный вечер, но одно — ваш комп не слабо подтормаживает, а указатель мыши показывает вам слайд-шоу. Это может быть кто-то из тех пользователей, которые «крадут» драгоценное время своими научными экспериментами, веб-серверами и другими гиковскими штучками.
Нет проблем, получим список всех процессов, которые запустили не вы:
ps aux —sort=-%cpu | grep -m 11 -v `whoami`
2. Замена текста в файлах
Сложность: средняя
Приложение: find/Perl
Если надо заменить текст не в одном файле, то есть несколько способов. Для того, чтобы заменить текст «Windows» на «Linux» во всех файлах в текущей директории, название которой начинается с «test», введите в консоли:
perl -i -pe ‘s/Windows/Linux/;’ test*
find. -name ‘*.txt’ -print | xargs perl -pi -e’s/Windows/Linux/ig’ *.txt
find -type f -name ‘*.txt’ -print0 | xargs —null perl -pi -e ‘s/Windows/Linux/’
Сохраните немало времени и получите статус гуру Линкуса.
3. Исправить консоль
Сложность: легкая
Приложение: bash
Если использовать команду less или cat для просмотра файла, в конце которого — бинарные данные, то можно легко испортить консоль. Потому что в бинарных данных могут попасться любые сочетания управляющих кодов: компьютер будет издавать звуки «бип-бип», появятся прикольные символы, странные цветовые сочетания. В конце концов, шрифт изменится на какие-то иероглифы. Bash, очевидно, продолжает работать, но вы ничего не можете прочитать и не сделать. Просто наберите в консоли команду инициализации:
и все будет хорошо.
4. Создать keywords в Mozill’е
Сложность: легкая
Приложение: Firefox/Mozilla
Полезной особенностью Konqueror’а является возможность, набрав в адресной строке «gg onion», прогуглить слово onion. Тоже самое можно сделать в Firefox’е: сперва найдите меню Bookmarks>Manage Bookmarks и выберите Add a New Bookmark. Добавьте этот URL:
Выберите эту запись в редакторе закладок и откройте ее свойства. Введите в поле keyword gg — и все. Вместо %s будет подставлен текст после gg. Этот прием можно применить к другим сайтам, которые полагаются на данные в URL’е.
Другой вариант: сделайте клик правой кнопкой мыши в поисковом поле и выберите пункт меню Add a Keyword for this Search. . Появится окно, где можно задать keyword.
5. Запуск множественных X-сессий
Сложность: простая
Приложение: Х
Если надо дать кому-нибудь доступ к Вашему компьютеру, то вы может откроете для себя, что это не всегда необходимо. Если предположить, что компьютер стартует в графическом режиме (runlevel 5), то, одновременно нажав Ctrl+Alt+ , вы попадете в консоль. Введите логин и пароль, потом исполните следующий код:
чтобы воити в графическое окружение. Чтобы вернуться в предыдущую сессию, нажмите Ctrl+Alt+ , для еще одного возврата — Ctrl+Alt+ . Вы можете этот трюк: клавиши с F1 по F6 отвечают за 6 сессий консоли, а клавиши с F7 по F12 — за 6 Х-сессий. Подводный камень: в разных дистрибутивах могут использоваться разные сочетания клавиш.
6. Ускорение серфинга
Сложность: простая
Приложение: KDE
В KDE есть малоизвестная, но полезная опция для ускорения веб-серфинга. Запустите KDE Control Center и выберите System > KDE performanсe. Вы можете включить предварительную загрузку Konqueror’а. То есть браузер загрузится при запуске системы в фоновом режиме. Когда он потребуется, то появится практически мгновенно. Совет: прочитайте еще 20 подсказок для ускорения KDE
7. Легкое резервное копирование
Сложность: простая
Приложение: Backups
Если надо сделать резервную копию папки и скопировать только изменившиеся файлы, то можно использовать для этого rsync (вам нужен аккаунт на удаленном компьютере):
rsync -vare ssh jono@192.168.0.2:/home/jono/importantfiles/* /home/jono/backup/
Эта команда делает резервную копию всех файлов из /home/jono/backup/ в /home/jono/importantfiles/ на компьютере с IP-адресом 192.168.0.2
8. Поддерживать ваши часы в актуальном состоянии
Сложность: простая
Приложение: NTP
Если кажется, что ваши часы спешат или отстают, то используйте NTP для гарантированной синхронизации с очень высокой точностью. Необходимо установить NTP-пакет и потом произвести синхронизацию с сервером:
Список подходящих NTP-серверов можно найти на http://support.ntp.org/bin/view/Servers/NTPPoolServers. Добавьте эту команду в автозагрузку — и ваши часы всегда будут точными.
9. Поиск самых больших файлов
Сложность: низкая
Приложение: оболочка
Можно столкнуться с проблемой, когда надо удалить несколько больших файлов. Их можно найти в текущей директории с помощью команды:
10. Горячие клавиши Nautilus’а
Сложность: низкая
Приложение: Nautilus
Хотя в наши дни большинство файловых менеджеров должны поддерживать управление мышью, иногда полезно использовать клавиатуру. У Nautilus’а есть несколько сочетаний, которые позволяют мгновенно перемещаться между файлами:
— Открыть директорию — Ctrl+L
— Подняться на уровень выше — Ctrl+Up
— Перемещение внутри директории — стрелки
11. Оптимизация баз данных
Сложность: низкая
Приложение: MySQL
При любом изменении структуры базы данных или удалении больших объемов данных, файлы могут стать фрагментированными, что приводит к потере производительности. Просто запомните простое правило: запускать оптимизатор базы при любом изменении базы:
Вы можете заметить, что следует регулярно оптимизировать базы при использовании полей с типом VARCHAR: эти поля с переменной длиной особенно подвержены фрагментации.
12. Быстрые письма
Сложность: низкая
Приложение: KMail
Не можете позволить себе потерять 3 секунды на поиски вашего почтового клиента? Не устали от поиска указателя мыши среди всей красивой суматохи на вашем рабочем столе? Чтобы вы не делали в KDE, вас отделяет всего несколько нажатий клавиш от отправки письма. Нажмите Alt+F2 для открытия диалога ‘Run command’. Наберите:
Нажмите Enter — и KMail автоматически откроется. Вам даже необязательно набирать полный почтовый адрес. Этот трюк работает также и с Интернет-адресами: просто наберите www.hab.ru для запуска Konqueror’а.
13. Распараллеливание сборки
Сложность: низкая
Приложение: GCC
Если у вас многоядерная система с приличным количеством оперативной памяти, то можно значительно увеличить скорость при помощи параллельной сборки. Если сравнивать с последовательной сборкой, то прирост скорости в несколько раз. Для того, чтобы использовать два и более потока, добавьте ключ -j:
make -j4; make -j4 modules
14. Увеличение время работы батареи
Сложность: средняя
Приложение: hdparm
Вы вероятно сталкивались с hdparm для тюнинга жесткого диска, но это также может увелитчить время работы батареи вашего ноутбука и снизить шум вращающихся деталей.
hdparm -y /dev/hdb
hdparm -Y /dev/hdb
hdparm -S 36 /dev/hdb
Первая команда заставляет перейти в режим ожидания, вторая — в спящий режим, а последняя выставляет время автоматического выключения. Числовой параметр кратен 5.
15. Управление скоростью беспроводного подключения
Сложность: средняя
Приложение: iwconfig
Скорость, на которой радио-приемник и передатчик могут взаимодействовать, зависит от силы сигнала. Для того, чтобы поддерживать связь при ухудшении сигнала, данные должны передаваться с меньшей скоростью. Обычно, радио пытается вычислить доступный сигнал и автоматически выбирает наибольшую скорость передачи.
В областях интерференции с недостаточным уровнем сигнала, пакеты могут самопроизвольно пропадать, при этом приемник и передатчик постоянно регулируют скорость. Если нельзя добавить антенны или переместить ваше оборудование для усиления сигнала, то надо уменьшить скорость синхронизации. Это означает меньшее количество переподключений и может быть значительно быстрей, чем триггерное (flip-flop) соединение. У каждой сетевой карты свой способ установки соединения. В Линуксе ограничение скорости можно задать через iwconfig:
iwconfig eth0 rate 2M
iwconfig eth0 rate 5.5M auto
iwconfig eth0 rate auto
Сетевые карты могут работать на больших расстояниях при скорости 1Mbps, чем при скорости 11Mbps. Разница между 1Mbps и 11Mbps — 12 децибел для карт Orinocco, т.е., теоретически, можно увеличить максимальную дистанцию работы в 4 раза, уменьшив скорость передачи.
16. Список откртых портов
Сложность: средняя
Приложение: nestat
Получить список открытых портов в состоянии Listen очень просто в Линуксе:
# netstat -lnp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:5280 0.0.0.0:* LISTEN 698/perl
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 217/httpd
tcp 0 0 10.42.3.2:53 0.0.0.0:* LISTEN 220/named
tcp 0 0 10.42.4.6:53 0.0.0.0:* LISTEN 220/named
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 220/named
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 200/sshd
udp 0 0 0.0.0.0:32768 0.0.0.0:* 220/named
udp 0 0 10.42.3.2:53 0.0.0.0:* 220/named
udp 0 0 10.42.4.6:53 0.0.0.0:* 220/named
udp 0 0 127.0.0.1:53 0.0.0.0:* 220/named
udp 0 0 0.0.0.0:67 0.0.0.0:* 222/dhcpd
raw 0 0 0.0.0.0:1 0.0.0.0:* 7 222/dhcpd
В этом примере видно, что процесс с PID’ом 698 — процесс интерпретатора Перл, который слушает порт 5280. Если вы не рут в системе, то система не покажет пути к программам.
17. Увеличение скорости работы жестких дисков
Сложность: высокая
Приложение: hdparm
hdarm можно использовать для повышения производительности. Будьте осторожны: изменение этих настроек может привести к потере данных, поэтому предварительно сделайте резервную копию данных. Тестирование скорости можно произвести следующей команды:
hdparm -Tt /dev/sda
/dev/sda:
Timing cached reads: 1784 MB in 2.00 seconds = 892.56 MB/sec
Timing buffered disk reads: 82 MB in 3.04 seconds = 26.96 MB/sec
/dev/sda:
IO_support = 0 (default)
readonly = 0 (off)
readahead = 256 (on)
geometry = 4865/255/63, sectors = 78165360, start = 0
В большинстве дистрибутивов выбраны безопасные настройки, подходящие для большинства жестких дисков. Для того, чтобы увеличить скорость, можно включить DMA-режим. Большинство компьютеров поддерживают 3 режим — 32-битная передача данных, что увеличивает скорость почти в два раза:
18. Удаленный доступ к вашим программ.
Сложность: низкая
Приложение: X
Если необходим удаленный доступ к графическим приложениям, то это можно сделать с помощью SSH. Во-первых, надо включить эту опцию в /etc/ssh/sshd_config:
19. Более удобные маны
Сложность: низкая
Приложение: man
Если вы ищите информацию по определенной команде или тематике, то маны — хорошее место для начала поисков. Обычный доступ к манам — man , но можно искать нужные страницы по ключевому слову. Например, поиск манов, связанные с процессом входа в систему:
При чтении манов полезно использовать поиск: просто нажмите клавишу / и набирайте нужное слово.
20. Диаграмма взаимосвязи пакетов
Сложность: низкая
Приложение: Debian
Наиболее важная часть Debian’а — возможность устанавливать пакеты вместе со всеми зависимостями. Если вы хотите увидеть все взаимосвязи между пакетами, можно использовать пакет Graphiz из несвободного (non-free) репозитория Debian:
apt-cache dotty > debain.dot
21. Принудительное отключение занятых устройств
Сложность: низкая
Приложение: bash
Вам наверняка сталкивались с ситуацией, когда надо отмаунтить диск, но система при попытке отключения сообщает о том, что он занят. Одной командой можно узнать, какое приложение использует его:
Она показывает PID и команду запуска любого процесса, использующего /mnt/windows.
22. Конвертирование кодировок текстовых файлов
Сложность: низкая
Приложение: recode
recode — маленькая утилита, которая упростит перенос текстовых файлов, созданных на разных платформах. Одна из главных причин — различие переносов строк. В некоторых системах используется символ переноса строки, в других — символ возврата каретки, в остальных — оба способа. В итоге, если вы переносете текст с одной платформы на другую, то вы, открыв файл, увидете множество (или, наоборот, мало) переносов строк и много странных символов.
Параметры утилиты немного запутаны, но это можно обойти задав алиасы:
alias dos2unix=’recode dos/CR-LF..l1′
alias unix2win=’recode l1..windows-1250′
alias unix2dos=’recode l1..dos/CR-LF’
Существуют множество опций: recode может конвертировать тексты между рядом кодировок.
23. Поиск измененных сегодня файлов
Сложность: низкая
Приложение: различные
Например, утром вы создали файл, который именно сейчас очень нужен. Однако, вы не можете вспомнить его название. Вручную перебирать домашнюю директорию бессмысленно, где скопилась не одна тысяча файлов. Но есть небольшой прием, показывающий эффективность пайпов и объединения нескольких комманд консоли:
Параметры команды ls требуют вывода даты в определенном формате. Хитрость в том: то, что выдаст ls, идет на вход grep. Параметр grep сами по себе команда (заключена в обратные апострофы), которая подставляет текущую дату в шаблон для отсева. Ее легко модифицировать для поиска по другим датам, размеру файла и т.д.
Источник
21 Super Handy Linux Command Tips and Tricks That Will Save you a lot of Time and Increase Your Productivity
Brief: Here are some tiny but useful Linux commands, terminal tricks and shortcuts that will save you a lot of time while working with Linux command line.
Have you ever encountered a moment when you see your colleague using some simple Linux commands for tasks that took you several keystrokes? And when you saw that you were like, “Wow! I didn’t know it could have been done that easily”.
In this article, I’ll show you some pro Linux command tricks that will save you a lot of time and in some cases, plenty of frustration. Not only your friends or colleagues will ‘wow’ at you, it will also help you increase your productivity as you will need fewer keystrokes and even fewer mouse clicks.
It’s not that these are Linux tips for beginners only. Chances are that even experienced Linux users will find some hidden gems that they were not aware despite using Linux for all these years.
In any case, you learn Linux by experience, be it your own or someone else’s 🙂
Cool Linux terminal tricks to save time and increase productivity
You might already know a few of these Linux command tips or perhaps all of it. In either case, you are welcome to share your favorite tricks in the comment section.
Some of these tips also depend on how the shell is configured. Let’s begin!
0. Using tab for autocompletion
I’ll start with something really obvious and yet really important: tab completion.
When you are starting to type something in Linux terminal, you can hit the tab key and it will suggest all the possible options that start with string you have typed so far.
For example, if you are trying to copy a file named my_best_file_1.txt, you can just type ‘cp m’ and hit tab to see the possible options.
You can use tab in completing commands as well.
1. Switch back to the last working directory
Suppose you end up in a long directory path and then you move to another directory in a totally different path. And then you realize that you have to go back to the previous directory you were in. In this case, all you need to do is to type this command:
This will put you back in the last working directory. You don’t need to type the long directory path or copy paste it anymore.
2. Go back to home directory
This is way too obvious. You can use the command below to move to your home directory from anywhere in Linux command-line:
However, you can also use just cd to go back to home directory:
Most modern Linux distributions have the shell pre-configured for this command. Saves you at least two keystrokes here.
3. List the contents of a directory
You must be guessing what’s the trick in the command for listing the contents of a directory. Everyone knows to use the ls -l for this purpose.
And that’s the thing. Most people use ls -l to list the contents of the directory, whereas the same can be done with the following command:
Again, this depends on the Linux distributions and shell configuration, but chances are that you’ll be able to use it in most Linux distributions.
4. Running multiple commands in one single command
Suppose, you have to run multiple Linux commands one after another. Do you wait for the first command to finish running and then execute the next one?
You can use the ‘;’ separator for this purpose. This way, you can run a number of commands in one line. No need to wait for the previous commands to finish their business.
5. Running multiple commands in one single command only if the previous command was successful
In the previous command, you saw how to run several commands in one single command to save time. But what if you have to make sure that commands don’t fail?
Imagine a situation where you want to build a code and then if the build was successful, run the make?
You can use && separator for this case. && makes sure that the next command will only run when the previous command was successful.
A good example of this command is when you use sudo apt update && sudo apt upgrade to upgrade your system.
6. Easily search and use the commands that you had used in the past
Imagine a situation where you used a long command couple of minutes/hours ago and you have to use it again. Problem is that you cannot remember the exact command anymore.
Reverse search is your savior here. You can search for the command in the history using a search term.
Just use the keys ctrl+r to initiate reverse search and type some part of the command. It will look up into the history and will show you the commands that matches the search term.
By default, it will show just one result. To see more results matching your search term, you will have to use ctrl+r again and again. To quit reverse search, just use Ctrl+C.
Note that in some Bash shells, you can also use Page Up and Down key with your search term and it will autocomplete the command.
7. Unfreeze your Linux terminal from accidental Ctrl+S
You probably are habitual of using Ctrl+S for saving. But if you use that in Linux terminal, you’ll have a frozen terminal.
Don’t worry, you don’t have to close the terminal, not anymore. Just use Ctrl+Q and you can use the terminal again.
8. Move to beginning or end of line
Suppose you are typing a long command and midway you realize that you had to change something at the beginning. You would use several left arrow keystrokes to move to the start of the line. And similarly for going to the end of the line.
You can use Home and End keys here of course but alternatively, you can use Ctrl+A to go to the beginning of the line and Ctrl+E to go to the end.
I find it more convenient than using the home and end keys, especially on my laptop.
9. Delete entire line from cursor position
So many people either do not know about it or hardly use it.
In the Linux terminal, if you press Ctrl+U, it deletes everything from your current cursor position to the beginning of the line.
Similarly, if you press Ctrl+K, it deletes everything from your cursor position to the end of the line.
Possible made a mistake in typing the password? Instead of using backspace key all the way, simply use Ctrl+U and retype the password. You can discover plenty of other uses for these shortcuts.
10. Reading a log file in real time
In situations where you need to analyze the logs while the application is running, you can use the tail command with -f option.
You can also use the regular grep options to display only those lines that are meaningful to you:
You can also use the option F here. This will keep the tail running even if the log file is deleted. So if the log file is created again, tail will continue logging.
11. Reading compressed logs without extracting
Server logs are usually gzip compressed to save disk space. It creates an issue for the developer or sysadmin analyzing the logs. You might have to scp it to your local and then extract it to access the files because, at times, you don’t have write permission to extract the logs.
Thankfully, z commands save you in such situations. z commands provide alternatives of the regular commands that you use to deal with log files such as less, cat, grep etc.
So you get zless, zcat, zgrep etc and you don’t even have to explicitly extract the compressed files. Please refer to my earlier article about using z commands to real compressed logs in detail.
This was one of the secret finds that won me a coffee from my colleague.
12. Use less to read files
To see the contents of a file, cat is not the best option especially if it is a big file. cat command will display the entire file on your screen.
You can use Vi, Vim or other terminal based text editors but if you just want to read a file, less command is a far better choice.
You can search for terms inside less, move by page, display with line numbers etc.
13. Reuse the last item from the previous command with !$
Using the argument of the previous command comes handy in many situations.
Say you have to create a directory and then go into the newly created directory. There you can use the !$ options.
A better way to do the same is to use alt+. . You can use . a number times to shuffle between the options of the last commands.
14. Reuse the previous command in present command with !!
You can call the entire previous command with . This comes particularly useful when you have to run a command and realize that it needs root privileges.
A quick sudo !! saves plenty of keystrokes here.
15. Using alias to fix typos
You probably already know what is an alias command in Linux. What you can do is, to use them to fix typos.
For example, you might often mistype grep as gerp. If you put an alias in your bashrc in this fashion:
This way you won’t have to retype the command again.
16. Copy Paste in Linux terminal
This one is slightly ambiguous because it depends on Linux distributions and terminal applications. But in general, you should be able to copy paste in terminal with these shortcuts:
- Select the text for copying and right click for paste (works in Putty and other Windows SSH clients)
- Select the text for copying and middle click (scroll button on the mouse) for paste
- Ctrl+Shift+C for copy and Ctrl+Shift+V for paste
17. Kill a running command/process
This one is perhaps way too obvious. If there is a command running in the foreground and you want to exit it, you can press Ctrl+C to stop that running command.
18. Using yes command for commands or scripts that need interactive response
If there are some commands or scripts that need user interaction and you know that you have to enter Y each time it requires an input, you can use Yes command.
Just use it in the below fashion:
19. Empty a file without deleting it
If you just want to empty the contents of a text file without deleting the file itself, you can use a command similar to this:
20. Find if there are files containing a particular text
There are multiple ways to search and find in Linux command line. But in the case when you just want to see if there are files that contain a particular text, you can use this command:
I highly advise mastering find command though.
21. Using help with any command
I’ll conclude this article with one more obvious and yet very important ‘trick’, using help with a command or a command line tool.
Almost all command and command line tool come with a help page that shows how to use the command. Often using help will tell you the basic usage of the tool/command.
Just use it in this fashion:
Your favorite Linux command line tricks?
I have deliberately not included commands like fuck because those are not standard commands that you’ll find everywhere. The tricks discussed here should be usable almost in all Linux distributions and shell without the need of installing a new tool.
I would also suggest using alias command in Linux to replace complicated commands with a simple. Saves a lot of time.
I know that there are more Linux command tricks to save time in the terminal. Why not share some of your experiences with Linux and do share your best trick with rest of the community here? The comment section below is at your disposal.
Like what you read? Please share it with others.
Источник