Chapter-2 Command-Line Editing Continuedβ¦
π The fc command
The fc lets you edit and re-run a previous command using your preferred text editor.β
# To open the last command:
fc
# To open specific command number:
fc 10
- We use -l with fc command to list the previous commands.
# To list the last 16 commands:
fc -l
# To list history commands without numbers:
fc -ln
# To list history list from specific command number or a character in commands:
fc -l 15
fc -l l
# To list history list in specific range command numbers or characters:
fc -l 10 15
fc -l c h
fc -l c 20
- To edit commands using different editor
fc -e [Editor]
fc runs the command after editing automatically. Thus, need to be careful to avoid dangerous in scripts.
- The safer way is to redirect the history commands in a file and then edit and execute when ready.
fc -ln 5 > lastcommands
vi lastcommands
source lastcommands
- The fc with -s reruns the previous commands if no other arguments given. The command can be modified if required, along with string search.
#Rerun previous command
fc -s
# Rerun with editing with string search
cs /home
fs -s cs=cd cs
π§ Readline
π What Is Readline?
- A GNU library used by Bash and other text-based applications.
- Supports Emacs and Vi modes.
- Standardizes editing behavior across different programs.
- Allows user customization through configuration files.
Bash uses the Readline library to handle command-line editing. This powerful library enables text manipulation, key bindings, and custom editing behavior, giving Bash its editing capabilities.
βοΈ Readline Startup File β .inputrc
When bash starts up, it reads the startup file and any settings there come into effect.
The Readline library can be customized using a startup file called .inputrc located in your home directory:
~/.inputrc
- Each line binds a key to a function or macro.
π― Binding Keys
# Example: Binding CTRL-T
Control-t: end-of-line
#Or using escape sequence:
"\C-t": end-of-line
## RESULT: This makes CTRL-T move the cursor to the end of the line.
π― Binding Macros A macro is simply a sequence of keystrokes inside single or double quotes.
# Example: Binding CTRL-T with some text
"\C-t": "Curiouser and curiouser!"
π Escape Sequences in .inputrc
Sequence and their Meaning:
- \C- :Control key prefix
- \M- :Meta (Escape) key prefix
- \e :Escape character
- \\ :Backslash character(\)
- \<β> :Double quote (<β>)
- \β :Single quote (β)
π Conditional Settings You can write conditionals in .inputrc using:
$if
$else
$endif
- Examples:
# Only apply in Emacs mode
$if mode=emacs
"\C-t": "Curiouser and curiouser!"
$endif
# Terminal-specific key binding
$if term=xterm-256color
"\e[11~": beginning-of-line
$endif
# Bash-specific bindings
$if bash
"\C-x": kill-whole-line
$endif
# To test for bash specifics, put this in .inputrc
$if bash
π Readline Variables
These variables customize the behavior of shell editing experience. Can set them using the set
command inside .inputrc.
Here are some useful variables and what they do:
| Variable | Description |
| ββββββββ | βββββββββββββββββββββββββββββ |
| bell-style
| How the terminal signals errors: audible
, visible
, or none
. Default is audible
. |
| comment-begin
| The string inserted when using the insert-comment
command. Default is #
. |
| completion-query-items
| Number of possible completions shown before asking confirmation. Default: 100
. |
| convert-meta
| If On
, converts 8-bit characters into escaped ASCII. Default: On
. |
| disable-completion
| If On
, disables autocomplete. Default: Off
. |
| editing-mode
| Sets editing style: vi
or emacs
. Default is emacs
. |
| enable-keypad
| Enables keypad for special keys (like arrows). Needed on some systems. Default: Off
. |
| expand-tilde
| Enables tilde (~
) expansion in completions. Default: Off
. |
| horizontal-scroll-mode
| If On
, scrolls horizontally instead of wrapping long lines. Default: Off
. |
| input-meta
| If On
, allows 8-bit input. Synonym for meta-flag
. Default: Off
. |
| keymap
| Sets the keymap: options include emacs
, vi
, vi-insert
, etc. Default: emacs
. |
| mark-directories
| If On
, adds a trailing slash to completed directories. |
| mark-modified-lines
| If On
, adds *
to modified history lines. Default: Off
. |
| meta-flag
| Accepts 8-bit input (same as input-meta
). Default: Off
. |
| output-meta
| Displays 8-bit characters directly. Default: Off
. |
| show-all-if-ambiguous
| If On
, lists all matches instead of ringing the bell. Default: Off
. |
| visible-stats
| Adds file type characters (like /
, *
, etc.) in completion lists. Default: Off
. |
ποΈ Key Bindings Using bind
The bind
command allows to:
- Try out key bindings temporarily in the shell.
- View, set, or remove key bindings.
- Use the same syntax as .inputrc, but quoted on the command line
π Useful bind Options
| Command | Description |
| βββββββββ- | ββββββββββββββββββββ- |
| bind -P
| Prints all current key bindings along with the function name. |
| bind -l
| Lists all available readline function names. |
| bind -u function_name
| Unbinds all keys associated with the specified function. |
| bind -r keyseq
| Unbinds the specific key sequence. |
| bind -x '"keyseq":command'
| Binds a shell command to a key. |
| bind -p > .inputrc
| Saves current bindings into a .inputrc
-compatible format. |
| bind -f filename
| Reads key bindings from a file (like .inputrc
). |
π§ Keyboard Habits
β¨ Emacs Mode Is Easier for Beginners
- Emacs-mode uses intuitive Control key combinations
- No need to switch between βinsertβ and βcommandβ modes like in vi
- Simple for small-scale editing
β¨οΈ Essential Emacs-Style Key Bindings
| Key | Action |
| βββββ | βββββββββββ |
| CTRL-A
| Move to start of line |
| CTRL-E
| Move to end of line |
| CTRL-F
| Move forward (like right arrow) |
| CTRL-B
| Move backward (like left arrow) |
| CTRL-D
| Delete character under cursor |
| CTRL-K
| Delete to end of line |
| CTRL-P
/ β
| Previous command |
| CTRL-N
/ β
| Next command |
| CTRL-R
| Search command history |
| TAB
| Auto-complete filenames/commands |
Currently using VS Code
- Beginner-friendly and visually intuitive
- Auto-suggestions, syntax highlighting, error underlines
- Easy to edit and save .sh files
- Integrated terminal for running and debugging commands instantly
π Chapter 3 β Customizing Your Environment
A shell environment is like your digital workspace.
Your shell has:
- Files & directories
- Standard input/output
- Commands & tools
π§© 4 Key Customization Features in Bash Features and Purpose
- ποΈ Special Files : Run at login/logout/startup for setup tasks
- π Aliases : Shortcuts for long or repetitive commands
- βοΈ Options : Enable or disable shell behaviors
- π¦ Variables : Store values that affect shell/program behavior
1οΈβ£ Special Files
These are auto-executed scripts Bash reads at specific events:
Files and When it runs:
.bash_profile
: When you log in (for login shells)
After edits we can run the command
source .bash_profile
-
π Bash only reads one of the following at login, in order: - .bash_profile
- .bash_login
- .profile
</br>
-
.bashrc
: When a new terminal (interactive shell) is opened.
Read every time you open a new terminal, i.e., a subshell by typing bash on command line.
If some commands are set up in .bashrc
and want them to also run when you log in, then we can call .bashrc
from .bash_profile
using source command.
.bash_logout
: When you log out
Use it to clean up, log time, or remove some files. A goodbye message can also be put there by commands when logout. This is an optional file.
2οΈβ£ Aliases
Aliases let you create shortcuts for commands in command line , .bash_profile or .bashrc.
#Syntax
alias name=command
The aliases can be used for poor mneumonics or fix typos.
# To make meaning of mneumonic command
alias search=grep
# To fix some typos
alias gerp=grep
To short the long commands use quotes if multi-word command.
# Commonly used path in command line
alias cdbash='cd home/Documents/bash'
-
Special characters cannot be used in alias names.
-
Aliases can refer to other aliases.
#The alias can have another alias
alias printall='pr * | lpr'
alias pa='printall'
- It prevents alias with infinite loop.
#checks if the variable name is present in the value
alias stty='stty -a'
- Aliases can be used only for beginning of command string and not in between of command.
#if use cd and then alias for a pathname
alias video='/home/Desktop/Downloads/bash/video'
cd video
# This will not work
- Use quotes to make the value end with blank
alias cd='cd '
- The space in the end allows bash to look for other alias
cd video
# This will work
Some useful commands:
# To get list of alias
alias
# To get value of specific alias
alias name
# To remove the alias
unalias name
3οΈβ£ Options
Shell options control how the Bash shell behaves. These are settings that can be turned on or off to customize the shell environment.
- Enabling or Disabling Options (multiple options can be toggled)
# Turn ON an option
set -o optionname
# Turn OFF an option
set +o optionname
- Some have one-letter short forms
# Full form
set -o glob
# Short form
set -f
Useful Shell Options:
-
emacs
: Enables emacs-style command-line editing (default ON) -
ignoreeof
: Prevents logging out with CTRL-D; you must use exit -
noclobber
: Prevents overwriting existing files using > redirection -
noglob
: Disables wildcard expansion (*, ?) -
nounset
: Errors out if you use an undefined variable -
vi
: Enables vi-style command-line editing
To check status of all options with their settings
set -o
π shopt Command
A built-in as a better way to manage shell behavior.
- Basic Syntax
shopt [options] [option_names]
Options to shopt:
- -s : Set (enable) the option
- -u : Unset (disable) the option
- -p : Print list of options and their current values
- -q : Return status only, no output
- -o : Work with set -o compatible options
shopt -p
shopt
Shopt Option names
cdable_vars
: If argument to cd is not a directory, check if itβs a variable with a directory valuecheckhash
: Validates commands in the hash table still exist before executingcmdhist
: Saves multiline commands as a single history entrydotglob
: Includes hidden files (those starting with .) in glob patterns like *execfail
: Prevents shell exit when exec fails (non-interactive shells only)histappend
: Appends command history to file ($HISTFILE) instead of overwriting itlithist
: Stores multiline commands in history with newlines (depends on cmdhist being enabled)mailwarn
: Alerts if mail file was accessed since the last check
4οΈβ£ Shell Variables
Shell variables allow you to customize your environment by storing and using values throughout your session or scripts.
Syntax for defining
varname=value
# To delete the variable
unset varname
# To check variable value
echo "$varname"
- Using double quotes is preferred as it considers whole string as one.
π οΈ Built-In Variables
Editing Mode
These help customize how command history is saved and managed.
- To check max commands stored and max lines in history file
echo $HISTSIZE #1000
echo $HISTFILESIZE #2000
- Can also change the values
HISTFILESIZE=3000
βοΈ Reduce Clutter: HISTCONTROL
Control what goes into your history:
-
ignorespace
: Commands starting with space are ignored. -
ignoredups
: Ignore duplicates of the last command. -
erasedups
: Remove all earlier duplicates of the same command. -
ignoreboth
: Equivalent to ignorespace:ignoredups.
HISTCONTROL=ignorespace:ignoredups:erasedups
π― HISTIGNORE
Patterns for commands to ignore in history
- When donβt want commands like
ls
orclear
to be stored in history.
HISTIGNORE="ls:clear:&"
# use & to ignore the duplicates
β±οΈ Add Timestamps to History: HISTTIMEFORMAT
Adds the date and time when each command was run.
HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
# Then run
history
π¦ HISTCMD
: Current command number
echo $HISTCMD
FCEDIT
: Editor for fc command (default: vi)
π¬ Mail Variables in Bash (Legacy Feature)
πΈ This is a legacy feature. Itβs rarely used today and mostly relevant for older UNIX systems or mail-server setups.
πΈ Bash provides MAIL
, MAILCHECK
, and MAILPATH
to notify users about incoming mail β a useful feature back in the day of system mail. However, this is now not commonly used in modern Linux setups, especially where users rely on external email apps.
π₯οΈ Prompting Variables
Displays useful info like Current user, Directory, Time or date and Command number or history
Helps in scripting and multi-user environments.
Makes the shell more user-friendly and personalized.
πΈBash Prompt String Variables
πΉ PS1
: Primary prompt strings (default prompt when waiting for user input)
By default, the bash shell uses a prompt defined by the variable PS1. The default value of PS1 is:
\s-\v\$
- In most modern Linux systems like Ubuntu, the prompt is customized using colors and extra information
echo $PS1
πΉ PS2
: Secondary prompt String (used when a command is incomplete)
The default value is β>β.
πΉ PS3
and PS4
relate to shell programming and debugging.
π Common Prompt Escape Sequences:
- \u :Username
- \h : Hostname (short)
- \H : Full hostname
- \w : Current working directory
- \W : Basename of current directory
- \t : Current time (HH:MM:SS)
- \d : Date (Weekday Month Day)
- \! : History number of the command
- \# : Command number
- \$ : $ for normal user, # for root
- \n : Newline
- \@ : 12-hour time with am/pm
- \A : 24-hour time (HH:MM)
and moreβ¦
π Command search PATH
:
- PATH variable helps shell to find the commands entered.
- Every command is actually a file stored somewhere in the system usually under directories
- The shell uses a special environment variable called PATH to know where to search for these executable files.
echo $PATH
- Own scripts can be added in a personal directory and add that directory to your PATH in .bash_profile
β Safe Method (Append at End):
PATH=$PATH:/home/you/bin
β Risky Method (Prepend)
PATH=/home/you/bin:$PATH
type command
will either give the full pathname or the command with its type
type pwd
π§ Command Hashing
Bash creates a hash table to remember the location of commands that are already used, making the repeated command execution much faster.
# To view hash table
hash
-
Hits = number of times the command has been run in this session.
-
Some of the options for the hash are:
# Force adding a command to the hash
hash command
# Clear the hash table
hash -r
# Remove one command
hash -d command
# Insert command path to hash table
hash -p pathname
# To turn on or off command hashing
set -o hashall #Turn on
set +o hashall #Turn off
π§ Directory Search Path and Variables
What Is
CDPATH
?CDPATH
is likePATH
, but for thecd
command. Saves time if you frequently switch between any subfolders.
- If
CDPATH
isnβt set,cd
only checks the current directory.
cd dirname
- A shorthand feature that allows to use variable names with
cd
.
shopt -s cdable_vars
β‘οΈ Miscellaneous Variables
These serve as status indicators and for various other miscellaneous purposes.
π Table: Key Miscellaneous Shell Variables
Variable | Meaning |
---|---|
HOME |
Your home directory |
SECONDS |
Time (in seconds) since shell started |
BASH |
Full path of the Bash binary |
BASH_VERSION |
Bash version (as a string) |
BASH_VERSINFO |
Array of version parts (e.g., major, minor) |
PWD |
Present working directory |
OLDPWD |
Previous directory (before last cd ) |
π Customization and Subprocesses
When you enter a command in the terminal, the shell runs it in a subprocess thath has access to only some of your shellβs data. What gets passed to subprocesses can be customized.
π Key Question β Which shell variables are known to subprocesses?
βοΈ Answer: Only environment variables are automatically inherited that is known to all subprocesses. β Subprocesses canβt modify the processes that created them.
π Environment Variables
Environment variables are visible to subprocesses.
-
Some built-in variables are: HOME, PATH, MAIL, PWD, TERM, EDITOR
-
For text editors to know what kind of terminal you are using.
echo $TERM
π§΅ Making a Variable an Environment Variable There are two ways:
- Define first, then export
varname=value
export varname
- Define and export in one line
export varname=value
- Define variable in particular Subprocess
varname=value command
-
Mostly
.bash_profile
files include definitions of environment Pvariables -
To see all environment variables and their values
export
export -p
```bash
π Common Standard Environment Variables
Variable | Description |
---|---|
COLUMNS |
Width of your terminal (auto-set) |
LINES |
Height of your terminal (auto-set) |
EDITOR |
Preferred text editor path |
SHELL |
Path of your login shell |
TERM |
Type of terminal youβre using |
Terminal Types
TERM
is an environment variable that tells programs what kind of terminal youβre using.
- Crucial for screen-based programs.
echo $TERM
π§ Why Is TERM
Important?
Programs use TERM
to figure out:
- How to move the cursor
- How to scroll or clear the screen
- How to display colors, bold, or reverse video
If TERM
is set incorrectly:
- Programs might misbehave (e.g., garbled display)
The TERM
appear as short character string with lowercase letters filname in terminfo Database
- Located at: /usr/lib/terminfo
-
Contains binary files that describe each terminal
- If for some reason screen-based programs behave oddly, itβs often because the
TERM
variable isnβt set correctly. Normally, your terminal handles it, but if needed, you can manually check or change it using theecho
orexport
command.
There are some additional environment variables that help programs work correctly based on your preferences or system setup. For example:
-
EDITOR
tells programs like mail or crontab which text editor to use. -
SHELL
indicates your login shell, whileBASH
gives the path to the current shell instance. -
COLUMNS
andLINES
help screen-based programs format content correctly.
These variables are usually set automatically, but can export the changes in .bash_profile if needed.
The Environment File
To manage your shell environment, Bash uses two key files:
-
.bash_profile
: Runs only at login. Use it for setting environment variables and export commands. -
.bashrc
: Runs every time a new shell session starts. This is where we put aliases, functions, and options.
This is default environment file of bash. -
If add definitions in
.bashrc
put at end in.bash_profile
:
source ~/.bashrc
β Customization Hints
Instead of opening a text editor, just use echo
to append the line:
echo 'PS1="\u \!--> "' >> ~/.bash_profile
- Adds the prompt customization directly to your file.
- Use single quotes and the double right-angle bracket (Β») to avoid overwriting the file.