Bash Tips: History

Linux Bash

Bash keeps a history of the commands you type in and saves them to ~/.bash_history. These commands can be accessed in many ways and there are a lot of configuration related on how they are saved. I’ll cover some basic functionality here.

Event Designators (!, !!, !*)

From MAN Pages

An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list.

For the different examples below, assume we are running it against the same command (netstat -an | grep ':22'). This is to help you visualize the differences between each of the event designators.

Repeating the last command that starts with !string

You can run the most recent command starting with string by using !string.

$ !netstat
netstat -an | grep ':22'
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::22000                :::*                    LISTEN     
tcp6       0      0 :::22

Another example:

$ ls my_file.txt
.rw-r--r--     0 victor users 18 Oct 11:35  my_file.txt

$ ls my_folder
drwxr-xr-x     - victor users 18 Oct 11:35  my_folder

$ !ls
ls my_folder
drwxr-xr-x     - victor users 18 Oct 11:35  my_folder

Tip: you can use the :p option to print the command instead of running it

$ !netstat:p
netstat -an | grep ':22'

Repeating the same command with !!

As you may already know, the !! can be used for repeating the same command.

$ echo !!
echo netstat -an | grep ':22'

This is useful when you forget to use sudo on a command that requires sudo access.

For example:

$ systemctl daemon-reload
Failed to reload daemon: Access denied

$ sudo !!
sudo systemctl daemon-reload
[sudo] password for victor:

Re-using the last argument with !$

Another very useful option is the !$, which provides quick access to the last argument in a command.

$ echo !$
echo ':22'

This can come in handy if you need to repeat the last argument with another command.

$ touch my_new_script.sh

$ vim !$
vim my_new_script.sh

Another example:

$ mkdir myfolder

$ cd !$

The fc command

The command fc allows you to open commands in your history with an editor, modify the commands and then execute the modified version. It will use your default editor (as per $EDITOR), so make sure that is set.

Some common usage for fc:

  • fc -l - List your last commands
  • fc n - Edit the n command
  • fc -1 - Edit the last command
  • fc 20 22 - Edit commands 20 to 22

History Settings

On this section we talk a little bit about some of the configuration available for your Bash history.

Adds time to each command in history

# Sets up time for history
export HISTTIMEFORMAT="+%Y/%m/%d %T "

For example:

$ history | tail -n 10
  949  +2019/03/11 00:32:53 ssh seedbox
  950  +2019/03/11 16:05:53 cd .config/polybar
  951  +2019/03/11 16:05:56 ./launch.sh
  952  +2019/03/11 17:49:38 lolbanner victor
  953  +2019/03/11 17:53:10 lolbanner test
  954  +2019/03/11 17:53:11 psg checkupdates
  955  +2019/03/11 17:53:11 clear
  956  +2019/03/11 17:53:11 echo hello 1
  957  +2019/03/11 17:53:11 history
  958  +2019/03/11 18:10:01 history | tail -n 10

Avoid duplicate entries

# Avoid duplicates
export HISTCONTROL=ignoredups:erasedups

Append entries

This comes in handy if you run multiple terminal emulators simultaneously. By default, the latest closed terminal emulator will overwrite history from the other windows. With this setting, changes are appended making sure all commands are saved to history.

# When the shell exits, append to the history file instead of overwriting it
shopt -s histappend

Colorful Banners With figlet and lolcat

Linux Bash

Banners in *nix like systems is something that is being used for a very long time. System admins would sometimes use it to let users know that the system was going down (nowadays built-in with the shutdown command), or setup motd messages for SSH logins. Within the past years people got very creative with the use of different fonts and ASCII art.

For today’s post we will work With two different apps to display beautiful banners on your systems or config/dot files:

  • figlet - displays the banners
  • lolcat - colorizes the banners

Installation (Arch)

pacman -Sy figlet lolcat

figlet

Figlet comes with a default font and you can start using it right away

$ figlet "Hello World"
 _   _      _ _        __        __         _     _
| | | | ___| | | ___   \ \      / /__  _ __| | __| |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |
|_| |_|\___|_|_|\___/     \_/\_/ \___/|_|  |_|\__,_|

You can also download additional fonts (which is what we want). This will allow you to create a huge variety of banners.

Head over to the figlet-fonts project and take a look at the font files (*.flf). I would advise downloading the 3d.flf because that’s what we will use here. You can also clone the whole repo.

Place the new font in ~/.local/share/fonts/ and give it as an argument to the -f option in figlet:

$ figlet -f ~/.local/share/fonts/3d.flf "Hello World"
 ██      ██          ██  ██            ██       ██                  ██      ██
░██     ░██         ░██ ░██           ░██      ░██                 ░██     ░██
░██     ░██  █████  ░██ ░██  ██████   ░██   █  ░██  ██████  ██████ ░██     ░██
░██████████ ██░░░██ ░██ ░██ ██░░░░██  ░██  ███ ░██ ██░░░░██░░██░░█ ░██  ██████
░██░░░░░░██░███████ ░██ ░██░██   ░██  ░██ ██░██░██░██   ░██ ░██ ░  ░██ ██░░░██
░██     ░██░██░░░░  ░██ ░██░██   ░██  ░████ ░░████░██   ░██ ░██    ░██░██  ░██
░██     ░██░░██████ ███ ███░░██████   ░██░   ░░░██░░██████ ░███    ███░░██████
░░      ░░  ░░░░░░ ░░░ ░░░  ░░░░░░    ░░       ░░  ░░░░░░  ░░░    ░░░  ░░░░░░

lolcat

Lolcat produces a rainbow effect on terminal text. For example, try listing a directory and then piping it to lolcat. It should produce an output similar to the one below:

Putting it all together

Use the same figlet command we used before to print out «Hello World» and pipe it through lolcat to get the result below:

Optionally, you can add Bash alias/function to quickly display colorized banners:

lolbanner ()
{
    echo
    figlet -f ~/.local/share/fonts/3d.flf $* | lolcat
    echo
}

Have fun adding banners to your dot files, config files and screenshots/videos. Just remember that for config files, the colors will not be saved/shown.

Fzf for the Win

Linux Bash fzf

fzf is a command line fuzzy finder that can be used to automatically filter a list of items. Think of it as an interactive search tool, where items get filtered as you type characters in your terminal.

The video below shows a basic interaction using a list or files from the fd search utility:

fzf can also be used with other Bash tasks, like history, ssh and even file/dir completion. The GitHub page has a lot documentation on how to implement auto completion.

You can also use the --preview option to output the current selection into a preview box, and even call a command to be used with that value. For example, we can preview all the files in a folder by searching for files (with find or fd), piping the output to fzf, and then using a program like cat (on the example below I’m using bat, which is a clone of cat with the addition of syntax highlight and other cool things) to preview the files.

fd -d 1 -t f | fzf --preview 'bat --color "always" {}' --preview-window=right:60%

I’ve covered only the very basic usage for fzf, but it should give you an idea of how powerful this finder utility is. On future posts I’m going to cover other use cases, like the git workflow that I use.


References:

Bash Theme Powerline 2column

Bash Linux

powerline-2column is a simple powerline like prompt for Bash that displays information in two columns.

The prompt provides the following information:

Left Side

  • Folder icon for:
    • Git folder with provider icon
    • Home folder
    • Dropbox folder
  • Username
  • Hostname (when connecting via SSH)
  • Current path
  • Git status
    • untracked
    • uncommited
    • ahead/behind

Right Side

  • Previous exit code
  • Battery status
  • sudo cached credentials
  • Time

Check out some of the things it can do on the video below.

You can download a copy from my GitHub repo - https://github.com/victorbrca/powerline-2column

Count Lines of Codes With Cloc

Linux Programming

Have you ever had the nead to count the lines of code in a project or a folder? If you did, or want to, cloc is a neat utility that can help with just that.

As per it’s description on the GitHub page, «cloc counts blank lines, comment lines, and physical lines of source code in many programming languages». It displays a summary of file types and counted files, and then it breaks down a list of lines of code per language.

Here’s the output from my bash-config project:

 ~/Git/bash-config $ cloc .
      45 text files.
      43 unique files.                              
       4 files ignored.

github.com/AlDanial/cloc v 1.80  T=0.29 s (146.6 files/s, 10151.3 lines/s)
--------------------------------------------------------------------------------
Language                      files          blank        comment           code
--------------------------------------------------------------------------------
Bourne Again Shell               38            355            440           1525
Bourne Shell                      2             41             32            276
Markdown                          2             52              0            187
--------------------------------------------------------------------------------
SUM:                             42            448            472           1988
--------------------------------------------------------------------------------

And here’s a view of a more complex project with multiple languages:

     346 text files.
     338 unique files.                                          
     110 files ignored.

github.com/AlDanial/cloc v 1.80  T=0.75 s (319.4 files/s, 45153.6 lines/s)
----------------------------------------------------------------------------------------
Language                              files          blank        comment           code
----------------------------------------------------------------------------------------
Bourne Shell                            102           3417           3753          14810
Bourne Again Shell                       28           1209           1040           5480
XML                                       3             88             13            713
DOS Batch                                 6             90             24            448
Markdown                                  5            122              0            411
Visual Basic                              5             56             31            331
ERB                                      66             69              0            322
HTML                                      4             12             62            182
SQL                                      10             65            203            166
Korn Shell                                2             33             65            115
Velocity Template Language                1              0              0            114
Python                                    3             18             45             59
CSS                                       1              1              1             24
Java                                      1              3              3             22
Ruby                                      1              6              5             11
----------------------------------------------------------------------------------------
SUM:                                    238           5189           5245          23208
----------------------------------------------------------------------------------------

cloc is available on many distros default repo, as well as npm install. To install it use:

sudo apt install cloc                  # Debian, Ubuntu
sudo yum install cloc                  # Red Hat, Fedora
sudo dnf install cloc                  # Fedora 22 or later
sudo pacman -S cloc                    # Arch
sudo emerge -av dev-util/cloc          # Gentoo https://packages.gentoo.org/packages/dev-util/cloc
sudo apk add cloc                      # Alpine Linux
sudo pkg install cloc                  # FreeBSD
sudo port install cloc                 # Mac OS X with MacPorts
brew install cloc                      # Mac OS X with Homebrew
choco install cloc                     # Windows with Chocolatey
scoop install cloc                     # Windows with Scoop
code with