Dot bashrc

Last edited on 2022-01-09 Tagged under  #bash   #linux 

Interactive shells source a user's .bashrc and read commands from its standard input, ie a terminal (Debian also sources .bashrc from .profile). See man bash and INVOCATION for more details.

Customizing ~/.bashrc allows me to craft a more desirable prompt, create functions and aliases for oft-used commands, enable unlimited history, and tweak default settings to my preferences.

Prompt

I like a bit of colour in my prompt. First, I add some colour codes to my palette ...

# Colour codes
RED="\\[\\e[1;31m\\]"
GREEN="\\[\\e[1;32m\\]"
YELLOW="\\[\\e[1;33m\\]"
BLUE="\\[\\e[1;34m\\]"
MAGENTA="\\[\\e[1;35m\\]"
CYAN="\\[\\e[1;36m\\]"
WHITE="\\[\\e[1;37m\\]"
RESET="\\[\\e[0m\\]"

I set a two-line prompt (details on the first line; $ on the second with lots of space for input). If accessing console via ssh I include an ssh-session message in the prompt ...

PS1="${MAGENTA}\\u ${WHITE}at ${GREEN}\\h${YELLOW}${ssh_message} ${WHITE}in ${BLUE}\\w \\n$WHITE\$${RESET} "
if [[ -n "$SSH_CLIENT" ]]; then
    ssh_message="-ssh_session"
fi
PS1="${GREEN}\\u ${WHITE}at ${YELLOW}\h${RED}${ssh_message} ${WHITE}in ${BLUE}\\w \\n$WHITE\$${RESET} "

Functions

Backup and timestamp files ...

bak() { for f in "$@"; do cp "$f" "$f.$(date +%FT%H%M%S).bak"; done; }

List my top 10 most used commands (which make good candidates for single-letter aliases) ...

cmd10() { history | awk '{print $3}' | sort | uniq -c | sort -rn | head; }

One of my most frequently used command sequences is to change directories, then immediately list directory contents. This function does both by entering a single-letter command followed by directory name ...

c() { cd "$@" && ls -aFlhv --color=always; }

Make a directory and change to it immediately ...

md() { mkdir -p "$@" && cd "$@" || return; }

Clean up filenames by replacing spaces and non-ascii characters in a filename with underscore ...

mtg() { for f in "$@"; do mv "$f" "${f//[^a-zA-Z0-9\.\-]/_}"; done; }

"Mind the gap" (mtg) ... I remember hearing this when riding the tube in London!

Aliases

Debian-specific

Update repositories, perform a full-upgrade, clean package cache and remove packages no longer required by any other package ...

alias aaa="sudo apt update && apt list --upgradable && sudo apt full-upgrade && sudo apt-get autoclean && sudo apt autoremove"

Search to determine if a package is installed ...

alias dpkgg="dpkg -l | grep -i"

Distro-independent

A few other handy aliases ...

alias dff="df -hT --total"
alias tmuxd="tmux new -s default -A"
alias e="nvim"
alias l="ls -aFlhv --color=always"
alias p="less -R"
alias x="exit"

History

Disable truncating Bash history and save everything ...

# Unlimited history.
HISTSIZE=
HISTFILESIZE=

Change the history file location because certain bash sessions truncate ~/.bash_history upon close ...

HISTFILE=~/.bash_unlimited_history

Default is to write history at the end of each session, overwriting the existing file with an updated version. If logged in with multiple sessions, only the last session to exit will have its history saved.

Require prompt write to history after every command and append to the history file, don't overwrite it ...

shopt -s histappend
PROMPT_COMMAND="history -a; $PROMPT_COMMAND"

Now you can see the commands from all shells in near real-time in ~/.bash_unlimited history. Starting a new shell displays the combined history from all terminals.

Add a timestamp per entry. Useful for context when viewing logfiles ...

HISTTIMEFORMAT="%FT%T  "

Save all lines of a multiple-line command in the same history entry ...

shopt -s cmdhist

Re-edit a history substitution line if it failed ...

shopt -s histreedit

Edit a recalled history line before executing ...

shopt -s histverify

Do not put lines starting with space in the history ...

HISTCONTROL=ignorespace

Toggle history off/on for a current shell ...

alias stophistory="set +o history"
alias starthistory="set -o history"

These links were helpful configuring the unlimited history: BASH history truncated to 500 lines on each login and Preserve bash history in multiple terminal windows.

Extras

PROMPT_COMMAND sets the terminal title bar ...

export PROMPT_COMMAND='printf "\033]0;%s at %s\007" "${USER}" "${HOSTNAME%%.*}"'

When resizing a terminal emulator, check the window size after each command and, if necessary, update the values of LINES and COLUMNS ...

shopt -s checkwinsize

Use keychain for ssh-agent management ...

if [[ -x /usr/bin/keychain ]]; then
	keychain ~/.ssh/id_ed25519
	. "${HOME}/.keychain/${HOSTNAME}-sh"
fi

Disable XON/XOFF flow control. Enables use of Ctrl-S in other commands. Examples: forward search in history; disable screen freeze in vim ...

stty -ixon

Bash completion ...

if [[ -f /etc/profile.d/bash_completion.sh ]]; then
    # shellcheck source=/dev/null
    . /etc/profile.d/bash_completion.sh
fi

Automatically search (after first installing the command-not-found package) the official repositories when entering an unrecognized command ...

if [[ -f /usr/share/doc/pkgfile/command-not-found.bash ]]; then
    . /usr/share/doc/pkgfile/command-not-found.bash
fi

When happy with the changes, save file and reload the config ...

$ . ~/.bashrc

Sources: .bashrc and .profile

Thanks for reading! Read other posts?

» Next: Generate a list of installed deb packages on one device (and install on another)

« Previous: Buster to Bullseye