Shell Customization
Variables
Quoting from article on BASH Environment & Shell Variables
Variables provide a simple way to share configuration settings between multiple applications and processes in Linux, and are mainly set in either a terminal or shell configuration file upon start up.
They are either environmental or shell variables by convention. Both of which are usually defined using all capital letters. This helps users distinguish environmental variables from within other contexts.
“Environment variables” have been defined for use in the current shell and will be inherited by any child shells or processes spawned as a result of the parent. Environmental variables can also be used to pass information into processes that are spawned by the shell
“Shell variables” are contained exclusively within the shell in which they were set or defined. They are mostly used to keep track of ephemeral temporal data, like the current working directory in a session
Some example Variables:
HOMEThe home directory of the current user; the default argument for thecdbuiltin command. The value of this variable is also used when performing tilde expansionSHELLThe full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, bash assigns to it the full pathname of the current user's login shellPATHThe search path for commands. It is a colon-separated list of directories in which the shell looks for commands. A common value is/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbinPWDandOLDPWDfull path of current working directory and previous working directoryHISTFILESIZE,HISTSIZE,HISTCONTROL,HISTFILEcommand history related variablesPS1The value of this parameter is expanded and used as the primary prompt string. The default value is\s-\v\$printenvcommand to display names and values of Environment variablessetbuiltin command to display the names and values of all the variables when used without options/argumentsecho "$HOME"use$when Variable value is needed
User defined variables
User can define variables as well - for temporary use, in shell script, etc.
Using lowercase is preferred to avoid potential conflict with shell or environment variables
$ #array of 8-bit binary numbers in ascending order
$ dec2bin=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
$ echo "${dec2bin[2]}"
00000010
$ echo "${dec2bin[120]}"
01111000
$ echo "${dec2bin[255]}"
11111111
Further Reading
- Section 'Shell Variables' in
info bash - Difference between shell and environment variables
- Variable behavior varies with different type of shells
- How to correctly modify PATH variable
- Read more on the dec2bin brace expansion example
- Parameter expansion - from simple ways to get Variable values to complicated manipulations
Config files
Through use of aliases, functions, shell variables, etc one can customize the shell as per their needs
From 'FILES' section in info bash
/etc/profileThe systemwide initialization file, executed for login shells/etc/bash.bashrcThe systemwide per-interactive-shell startup file/etc/bash.bash.logoutThe systemwide login shell cleanup file, executed when a login shell exits~/.bash_profileThe personal initialization file, executed for login shells~/.bashrcThe individual per-interactive-shell startup file~/.bash_logoutThe individual login shell cleanup file, executed when a login shell exits~/.inputrcIndividual readline initialization file
~/.bashrc
From 'INVOCATION' section in info bash
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.
shoptSet and unset shell optionsshopt -s autocdchange directory by typing just the name, without having to explicity type thecdcommand (-ssets/enables this option)shopt -u autocdunset/disable autocd optionshopt -s dotglobinclude files starting with.also for wildcard expansion- shopt builtin command
setSet or unset values of shell options and positional parametersset -o emacsUse emacs-style line editing interfaceset -o viUse vi-style line editing interfaceset -o historyenable command historyset +o historydisable command history, useful to temporarily disable logging command history for current session until it is re-enabledset -osee current status of various options - are they on/off- set builtin command
- aliases
- aliases and functions are generally used to construct new commands or invoke commands with preferred options
source ~/.bash_aliasesto avoid cluttering the bashrc file, it is recommended to put them in a separate file and usesourcecommand to add to bashrc
- history
- By default, history commands are stored in ~/.bash_history, can be changed using
HISTFILEvariable HISTSIZE=5000this variable affects how many commands are in history of current shell session. Use negative number for unlimited sizeHISTFILESIZE=10000this variable affects how many commands are stored in the history file. Use negative number for unlimited file sizeHISTCONTROL=ignorespace:erasedupsdon't save commands with leading space and erase all previous duplicates matching current command lineshopt -s histappendappend to history file instead of overwriting- using bash history efficiently
- common history across sessions
- By default, history commands are stored in ~/.bash_history, can be changed using
- Setting prompt using the
PS1variablePS1="$ "simple prompt '$ 'PS1="\s-\v\$ "default prompt, adds bash version number, for ex: 'bash-4.3$ 'PS1="\u@\h\\$ \[$(tput sgr0)\]"is way of saying to set the prompt as 'username@hostname$ '- easy way to generate PS1 - above example was generated using this site, has options to add color as well
- What does the ~/.bashrc file do?
- Distros like Ubuntu come with
~/.bashrcalready created with useful configurations likebash_completion - sample bashrc
~/.inputrc
Key bindings for command line (readline) are customized in this file. By default, emacs-style is on and can be changed using the set command as discussed in previous section
Some of the default key bindings are discussed later in this chapter
"\e[A": history-search-backwardup arrow to match history starting with partly typed text"\e[B": history-search-forwarddown arrow to search in forward direction"\C-d": unix-filename-ruboutCtrl+d to delete from cursor backwards to filename boundaryset echo-control-characters offturn off control characters like^C(Ctrl+C) from showing on screenset completion-ignore-case onignore case for Tab completionset show-all-if-ambiguous oncombines single and double Tab presses behavior into single Tab press- Simpler introduction to Readline
- discussion on GNU Readline library library allows user to interact/edit command line
- sample inputrc
~/.bash_aliases
Before creating an alias or function, use type alias_name to check if an existing command or alias exists with that name
aliasused without argument shows all aliases currently set, sorted in alphabetical orderalias c='clear'aliasclearcommand to just the single letterc- Note that there should be no white-space around = operator
alias b1='cd ../'alias b1 to go back one hierarchy abovealias app='cd /home/xyz/Android/xyz/app/src/main/java/com/xyz/xyzapp/'alias frequently used long paths. Particularly useful when working on multiple projects spanning multiple years- and if aliases are forgotten over the years, they can recalled by opening ~/.bash_aliases file or using
aliascommand
- and if aliases are forgotten over the years, they can recalled by opening ~/.bash_aliases file or using
alias oa='gvim ~/.bash_aliases'open aliases file with your favorite editoralias sa='source ~/.bash_aliases'useful to apply changes to current sessionalias ls='ls --color=auto'colorize output to distinguish file typesalias l='ls -ltrh'map favorite options, plus color output as previously set alias will be substituted forlsalias grep='grep --color=auto'colorize file names, line numbers, matched pattern, etcalias s='du -sh * | sort -h'sort files/directories by size and display in human-readable format\lsoverride alias and use original command by using the\prefixch() { man $1 | sed -n "/^\s*$2/,/^$/p" ; }simple command help (ch) function to get information on a command option- for example:
ch ls -F,ch grep -o, etc ch() { whatis $1; man $1 | sed -n "/^\s*$2/,/^$/p" ; }also prints description of command- ch does a much better job with capability to handle multiple options, multiple arguments, builtin commands, etc
- explainshell does even better
- for example:
o() { gnome-open "$@" &> /dev/null ; }open files with their default applications, discards output and error messages- for example:
o bashguide.pdf $1first positional argument$2second positional argument$@all the arguments
- for example:
- sample bash_aliases
Further Reading
- Sensible bash customizations
- shell config files
- command line navigation
- difference between bashrc and bash_profile
- when to use alias, functions and scripts
- what does rc in bashrc stand for
Emac mode Readline shortcuts
Ctrl+csends SIGINT signal, requesting the current running process to terminateCtrl+ccan also be used to abort the currently typed command and give fresh command promptCtrl+zsuspends the current running processTabthe tab key completes the command (even aliases) or filename if it is unique, double Tab gives list of possible matches if it is not uniqueset show-all-if-ambiguous oncombines single and double Tab presses behavior into single Tab press
Ctrl+rSearch command history. After pressing this key sequence, type characters you wish to match from history, then pressEsckey to return to command prompt or pressEnterto execute the commandEsc+bmove cursor backward by one wordEsc+fmove cursor forward by one wordEsc+Backspacedelete backwards upto word boundaryCtrl+aorHomemove cursor to beginning to promptCtrl+eorEndmove cursor to end of command lineCtrl+lpreserve whatever is typed in command prompt and clear the terminal screenCtrl+udelete from beginning of command line upto cursorCtrl+kdelete from cursor to end of command lineCtrl+tswap the previous two characters around- For example: if you typed sp instead of ps, press Ctrl+t when the cursor is to right of sp and it will change to ps
Esc+tswap the previous two words around!$last used argument- for example: if
cat temp.txtwas the last command used,rm !$will delete temp.txt file Esc+.will insert the last used argument, useful when you need to modify before execution. Also multiple presses allows to traverse through second last command and so on
- for example: if
Mouse scroll button clickhighlight text you want to copy and then press scroll button of mouse in destination to paste the text- to disable pasting text on
Mouse scroll button click, use thexinputcommand and get the number corresponding to your mouse.. say it is11 xinput set-button-map 11 1 0 3to disablexinput set-button-map 11 1 2 3to enable back
- to disable pasting text on