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
# 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
fc -e [Editor]

fc runs the command after editing automatically. Thus, need to be careful to avoid dangerous in scripts.

fc -ln 5 > lastcommands
vi lastcommands
source lastcommands
#Rerun previous command
fc -s

# Rerun with editing with string search
cs /home
fs -s cs=cd cs

🧠 Readline

πŸ“š What Is Readline?

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

🎯 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
# 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:

πŸ” 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

⌨️ 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

πŸ“š Chapter 3 – Customizing Your Environment

A shell environment is like your digital workspace.
Your shell has:

🧩 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:

After edits we can run the command

source .bash_profile

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.

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'
#The alias can have another alias
alias printall='pr * | lpr'
alias pa='printall'
#checks if the variable name is present in the value
alias stty='stty -a'
#if use cd and then alias for a pathname
alias video='/home/Desktop/Downloads/bash/video'
cd video
# This will not work
alias cd='cd '
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.

# Turn ON an option
set -o optionname

# Turn OFF an option
set +o optionname
# Full form
set -o glob

# Short form
set -f

Useful Shell Options:

To check status of all options with their settings

set -o

πŸ”Ž shopt Command

A built-in as a better way to manage shell behavior.

shopt [options] [option_names]

Options to shopt:

shopt -p
shopt

Shopt Option names

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"

πŸ› οΈ Built-In Variables

Editing Mode

These help customize how command history is saved and managed.

echo $HISTSIZE #1000
echo $HISTFILESIZE #2000
HISTFILESIZE=3000

βœ‚οΈ Reduce Clutter: HISTCONTROL

Control what goes into your history:

HISTCONTROL=ignorespace:ignoredups:erasedups

🎯 HISTIGNORE Patterns for commands to ignore 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

πŸ“¬ 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\$
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:

πŸ“Œ Command search PATH:

echo $PATH

βœ… Safe Method (Append at End):

PATH=$PATH:/home/you/bin

❌ Risky Method (Prepend)

PATH=/home/you/bin:$PATH
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
# 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 like PATH , but for the cd command. Saves time if you frequently switch between any subfolders.

cd dirname
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.

echo $TERM

🧡 Making a Variable an Environment Variable There are two ways:

  1. Define first, then export
varname=value
export varname
  1. Define and export in one line
export varname=value
varname=value command
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.

echo $TERM

🧠 Why Is TERM Important?

Programs use TERM to figure out:

If TERM is set incorrectly:

The TERM appear as short character string with lowercase letters filname in terminfo Database

There are some additional environment variables that help programs work correctly based on your preferences or system setup. For example:

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:

source ~/.bashrc

βœ… Customization Hints

Instead of opening a text editor, just use echo to append the line:

echo 'PS1="\u \!--> "' >> ~/.bash_profile