Enable advanced search in history mac windows linux

How To Search Shell Command History

Q. How do I search old command history under bash shell? How do I display or modify previous commands?

A. Almost all modern shell allows you to search command history if enabled by user. Use history command to display the history list with line numbers. Lines listed with with a * have been modified by user.

Shell history search command

Type history at a shell prompt:
$ history
Output:
Sample output:

To search particular command, enter:
$ history | grep command-name
$ history | egrep -i ‘scp|ssh|ftp’

Emacs Line-Edit Mode Command History Searching

To get previous command containing string, hit [CTRL]+[r] followed by search string:

To get previous command, hit [CTRL]+[p]. You can also use up arrow key.

To get next command, hit [CTRL]+[n]. You can also use down arrow key.

fc command

fc stands for either “find command” or “fix command. For example list last 10 command, enter:
$ fc -l 10
To list commands 130 through 150, enter:
$ fc -l 130 150
To list all commands since the last command beginning with ssh, enter:
$ fc -l ssh
You can edit commands 1 through 5 using vi text editor, enter:
$ fc -e vi 1 5

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Delete command history

The -c option causes the history list to be cleared by deleting all of the entries:
$ history -c

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

История команд Linux

В терминале Linux, кроме всего прочего, есть одна замечательная вещь. Это история команд Linux. Все команды, которые вы вводите во время работы сохраняются и вы можете найти и посмотреть их в любой момент. Также можете вернуться на несколько команд чтобы не набирать недавно выполненную команду заново.

В этой небольшой статье мы рассмотрим как пользоваться историей команд Linux, как ее настроить, а также рассмотрим полезные приемы, которые могут помочь вам в работе.

История команд Linux

Большинство задач, связанных с историей команд, мы будем выполнять либо с помощью команды history, либо с помощью оболочки. В истории хранится последняя 1000 команд, которые вы выполняли. Чтобы посмотреть всю историю для этого терминала просто запустите команду history без параметров:

Для дополнительных действий с историей вам могут понадобиться опции. Команда history linux имеет очень простой синтаксис:

$ history опции файл

В качестве файла можно указать файл истории. По умолчанию история для текущего пользователя хранится в файле

/.history, но вы можете задать, например, файл другого пользователя. А теперь рассмотрим опции:

  • -c — очистить историю;
  • -d — удалить определенную строку из истории;
  • -a — добавить новую команду в историю;
  • -n — скопировать команды из файла истории в текущий список;
  • -w — перезаписать содержимое одного файла истории в другой, заменяя повторяющиеся вхождения.

Наиболее полезной для нас из всего этого будет опция -c, которая позволяет очистить историю команд linux:

Так вы можете посмотреть только последние 10 команд:

А с помощью опции -d удалить ненужное, например, удалить команду под номером 1007:

Если вы хотите выполнить поиск по истории bash, можно использовать фильтр grep. Например, найдем все команды zypper:

history | grep zypper

На самом деле работать с историей еще более просто с помощью оболочки, возможно, вы уже используете многие ее функции, но о некоторых точно не знаете. Рассмотрим их:

Читайте также:  Windows auf usb stick

Чтобы показать предыдущую команду просто нажмите стрелку вверх, так можно просмотреть список раньше выполненных команд.

Вы можете выполнить последнюю команду просто набрав «!!». Также можно выполнить одну из предыдущих команд указав ее номер «!-2»

Чтобы выполнить поиск по истории прямо во время ввода нажмите Ctrl+R и начните вводить начало команды.

Если вы знаете, что нужная команда была последней, которая начиналась на определенные символы, например, l, то вы можете ее выполнить, дописав «!l»:

Если нужная команда последняя содержала определенное слово, например, tmp, то вы можете ее найти, использовав «!?tmp»:

Если вы не хотите, чтобы выполняемая команда сохранилась в истории просто поставьте перед ней пробел.

Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд bash хранит очень много команд и этого вполне достаточно для комфортной работы.

Настройка истории Linux

Linux — очень настраиваемая и гибкая система, поэтому настроить здесь можно все, в том числе и историю. По умолчанию выводится только номер команды, но вы можете выводить и ее дату. Для этого нужно экспортировать переменную HISTORYFORMAT вместе нужным форматом:

export HISTTIMEFORMAT=’%F %T ‘
$ history

Для форматирования можно использовать такие модификаторы:

  • %d – день;
  • %m – месяц;
  • %y – год;
  • %T – штамп времени;
  • %F — штамп даты.

Вы можете указать какие команды не стоит отображать, например, не будем выводить ls -l, pwd и date:

export HISTIGNORE=’ls -l:pwd:date:’

Также можно отключить вывод одинаковых команд:

Существует два флага, ignoredups и ignorespace. Второй указывает, что нужно игнорировать команды, начинающиеся с пробела. Если вы хотите установить оба значения, используйте флаг ignoreboth. Используйте переменную HISTSIZE, чтобы установить размер истории:

По умолчанию история сохраняется для каждого терминала отдельно. Но если вы хотите чтобы все ваши команды немедленно синхронизировались между всеми терминалами, то это очень просто настроить. Добавьте такую переменную:

export PROMPT_COMMAND=»$history -a; history -c; history -r;»

Для тестирования работы вы можете набирать эти команды прямо в терминале и сразу видеть результат, но для сохранения добавьте нужные строки в ваш

export PROMPT_COMMAND=»$history -a; history -c; history -r;»
$ export HISTCONTROL=ignoredups
$ export HISTTIMEFORMAT=’%F %T ‘

Готово, теперь осталось сохранить изменения и перезапустить ваши терминалы. Теперь ваша история будет выводить дату, игнорировать дубли и синхронизироваться между терминалами.

Выводы

В этой статье мы рассмотрели что такое история команд linux, как с ней работать, как применяется команда history linux и какие настройки можно использовать для более комфортной работы. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

ibLeDy / desktop_chromium_flags.md

Override software rendering list — Enabled

Overrides the built-in software rendering list and enables GPU-acceleration on unsupported system configurations. – Mac, Windows, Linux, Chrome OS, Android

Enable Reader Mode — Enabled

Allows viewing of simplified web pages by selecting ‘Customize and control Chrome’>’Distill page’ – Mac, Windows, Linux, Chrome OS

Smooth Scrolling — Enabled

Animate smoothly when scrolling page content. – Windows, Linux, Chrome OS, Android

Experimental QUIC protocol — Enabled

Enable experimental QUIC protocol support. – Mac, Windows, Linux, Chrome OS, Android

Experimental WebAssembly — Enabled

Enable web pages to use experimental WebAssembly features. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly baseline compiler — Enabled

Enables WebAssembly baseline compilation and tier up. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly lazy compilation — Enabled

Enables lazy (JIT on first call) compilation of WebAssembly modules. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly tiering — Enabled

Enables tiered compilation of WebAssembly (will tier up to TurboFan if #enable-webassembly-baseline is enabled). – Mac, Windows, Linux, Chrome OS, Android

GPU rasterization — Enabled

Use GPU to rasterize web content. Requires impl-side painting. – Mac, Windows, Linux, Chrome OS, Android

WebGL Draft Extensions — Enabled

Enabling this option allows web applications to access the WebGL Extensions that are still in draft status. – Mac, Windows, Linux, Chrome OS, Android

Zero-copy rasterizer — Enabled

Raster threads write directly to GPU memory associated with tiles. – Mac, Windows, Linux, Chrome OS, Android

Force Dark Mode for Web Contents — Enabled

Automatically render all web contents using a dark theme. – Mac, Windows, Linux, Android

Tab Groups Collapse Freezing — Enabled

Experimental tab freezing upon collapsing a tab group. – Mac, Windows, Linux, Chrome OS

Читайте также:  Как лучше установить windows 10 обновить или заново

Parallel downloading — Enabled

Enable parallel downloading to accelerate download speed. – Mac, Windows, Linux, Chrome OS, Android

Override software rendering list — Enabled

Overrides the built-in software rendering list and enables GPU-acceleration on unsupported system configurations. – Mac, Windows, Linux, Chrome OS, Android

Smooth Scrolling — Enabled

Animate smoothly when scrolling page content. – Windows, Linux, Chrome OS, Android

Experimental QUIC protocol — Enabled

Enable experimental QUIC protocol support. – Mac, Windows, Linux, Chrome OS, Android

Experimental WebAssembly — Enabled

Enable web pages to use experimental WebAssembly features. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly baseline compiler — Enabled

Enables WebAssembly baseline compilation and tier up. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly lazy compilation — Enabled

Enables lazy (JIT on first call) compilation of WebAssembly modules. – Mac, Windows, Linux, Chrome OS, Android

WebAssembly tiering — Enabled

Enables tiered compilation of WebAssembly (will tier up to TurboFan if #enable-webassembly-baseline is enabled). – Mac, Windows, Linux, Chrome OS, Android

GPU rasterization — Enabled

Use GPU to rasterize web content. Requires impl-side painting. – Mac, Windows, Linux, Chrome OS, Android

WebGL Draft Extensions — Enabled

Enabling this option allows web applications to access the WebGL Extensions that are still in draft status. – Mac, Windows, Linux, Chrome OS, Android

Zero-copy rasterizer — Enabled

Raster threads write directly to GPU memory associated with tiles. – Mac, Windows, Linux, Chrome OS, Android

Force Dark Mode for Web Contents — Enabled

Automatically render all web contents using a dark theme. – Mac, Windows, Linux, Android

Reading List — Enabled

Allow users to save tabs for later. Enables a new button and menu for accessing tabs saved for later. – Mac, Windows, Linux, Chrome OS, Android

Parallel downloading — Enabled

Enable parallel downloading to accelerate download speed. – Mac, Windows, Linux, Chrome OS, Android

Tab Grid Layout — Enabled

Allows users to see their tabs in a grid layout in the tab switcher on phones. – Android

Tab Groups — Enabled

Allows users to create groups to better organize their tabs on phones. – Android

Tab Groups Continuation — Enabled

Allows users to access continuation features in Tab Group on phones. – Android

Skia API for compositing — Enabled

If enabled, the display compositor will use Skia as the graphics API instead of OpenGL ES. – Windows, Linux, Android

This comment has been minimized.

Copy link Quote reply

vonDubenshire commented Oct 3, 2021

Love this! I even think a few more for Canary builds would be great to contribute to

This comment has been minimized.

Copy link Quote reply

ibLeDy commented Oct 3, 2021 •

Love this! I even think a few more for Canary builds would be great to contribute to

@vonDubenshire Thanks! I am actually considering that it may be better to move this to a repo, as it would be easier to maintan and to accept contributions too!

It would also allow for better user experience, as we could have a TOC, link to specific flags.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Searching your command history on macOS terminal

What is the shortcut to search my command history in macOS terminal?

For how long is the history available for searching? Where is it stored?

12 Answers 12

How about using Ctrl + R for searching on the Terminal Utility in Mac for searching on the command history,

Well for controlling how long the history would be retained that depends on a few shell environment variables, HISTFILESIZE which is nothing but number of lines of history you want to retain. Set a huge value for it in .bash_profile for it to take effect

Use Ctrl + R for searching a command from history in Terminal.

Type any substring of the command you want to search e.g. grep

It will return the latest command that matches your input. If that is not the command you were searching for, keep pressing Ctrl + R for next match until you find your command.

Читайте также:  Лучшие приложения для линукс 2020

Once you found your command press Return to execute it.

If you want to exit without running any command, press Ctrl + G

PS: This answer is same as suggested by Inian, just giving more details for easy usage.

The command history is stored under your home folder in a hidden file called .bash_history. To view it’s content in nano, use the following command in Terminal:

Or open with your text editor (default is TextEdit):

In my case it’s a very long list and as I scroll through seems like the last

500 command is stored here.

/.history depending on your shell.

Migrating an answer to SO from this answer on the Unix and Linux Stack Exchange:

Pressing ctrl + R will open the history-search-backward. Now start typing your command, this will give the first match. By pressing ctrl + R again (and again) you can cycle through the history.

If you like to be super lazy you can bind the up/down arrow keys to perform this search, I have the following in my .inputrc to bind the up/down arrow key to history-search-backward and history-search-forward :

Just type something (optional), then press up/down arrow key to search through history for commands that begin with what you typed.

To do this in .bashrc rather than .inputrc , you can use:

Use this command —

This works on both OSX and Linux.

History is stored in

/.history depending on your shell.

History is stored for 1000 or 2000 lines depending on your system.

/.zshrc for example in case of z shell.

You can also try the following:

Where ‘git’ is the command you are looking for.

For those who want to search specific command from history, you can do so with reverse-i-search . Reverse search allow you to type in any key words(any) that is part of the command you are looking for and reverse search navigate back to history, match previous commands incrementally and return the entire command.

It is especially useful as when one cannot remember all handy lengthy commands they use often. To do reverse-search ctrl + R and type any clue you have and that will return your previous commands matching the words you type. Then once found the command, hit Enter to execute it directly from search.

Since you mentioned viewing your history as a quick solution, via the Terminal.app. You might want to automate, or quickly view history, maybe from the dock. You may use the AppleScript application as one alternative. This is an optional approach to create a simple shortcut, as to many others.

  1. Open the AppleScript editor application.
  2. Add your specified commands, for history.
  3. Code
  1. Save as application, drag to dock for convenience.

History Storage & Time Stored Details

HISTSIZE Determines how many lines will be written to the history file.

HISTFILESIZE Determines how long the file.

Find out how long history is stored:

echo $HISTSIZE $HISTFILESIZE

Note: You may also increase your command history storage size in the length of two variables. You may achieve this through HISTSIZE and HISTFILESIZE environment variables which are located in your

It is possible to achieve this by modifying

/.bash_profile , the number placeholder with SIZE represent’s the number, lines value as example:

HISTFILESIZE will only set a maximum history value which is stored to the history file when a session is started. HISTSIZE will determine specifically how many lines will be stored or in other words, written at the end of the session. If the set HISTFILESIZE is determined to be a large value than what HISTSIZE is set, you will not view history larger than your set HISTSIZE . The reason is that the history file is overwritten with the HISTSIZE unless using histappend option turned ON.

You may use also histappend to append history, If the histappend shell option is turned on lines are appended to the history file. Otherwise, the overwritten alternative proceeds.

Modify history environment variables, set to a value:

Run the source command can be used to load any functions file into the current shell script or a command prompt.

Источник

Оцените статью