Skip to content

Linux Foundations / Find your way around Linux ยท Step 20 of 63

Lesson: historySwitch
โ† Linux Foundations

Shell and files

history

Recall, search and rerun earlier commands using the shell history.

Your shell remembers the commands you type, so you do not have to retype them. This lesson describes bash. Other shells such as zsh and fish have history too, with differences.

Looking at history

$ history
  501  cd /var/log
  502  ls -l
  503  history

Each line has a number and the command. Give a number to show only the most recent entries: history 10.

Using the keyboard

The Up arrow brings back the previous command, and Down moves forward again. You can edit the line before pressing Enter.

Press Ctrl+R and start typing to search backwards through history:

(reverse-i-search)`log': cd /var/log

Press Ctrl+R again for an older match, Enter to run it, or Ctrl+G to cancel.

History expansion

Bash replaces certain ! patterns before running a line:

  • !! is the previous command.
  • !502 is command number 502.
  • !ls is the most recent command starting with ls.

A common use:

$ apt update
$ sudo !!
sudo apt update

Bash prints the expanded line and then runs it. Be careful: it runs immediately. Add :p, as in !502:p, to print without running.

Where it is saved

Commands are kept in memory during the session and are normally written to ~/.bash_history when the shell exits. So two open terminals may not see each other's latest commands. The HISTSIZE variable controls how many are remembered.

Removing entries

history -d 502 deletes one entry and history -c clears the list in the current shell. history -c by itself does not rewrite the saved file there and then. To write the cleared list to the file, follow it with history -w.

Because history is stored as plain text, avoid typing passwords as part of a command. Some distributions set HISTCONTROL so that a line starting with a space is not recorded, but do not rely on it without checking:

$ echo $HISTCONTROL
ignoreboth

Try it

  1. Run history 5.
  2. Use the Up arrow to recall a command and edit it.
  3. Press Ctrl+R and search for part of an old command.
  4. Print a numbered entry with !N:p, replacing N with its number.

Check your understanding

history

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.