πŸ“š Bash Basics: β€œLearning the Bash Shell (3rd Edition)”

πŸš€ Introduction

user shell and os relation

πŸ“œ History of Bash

🌟 Features of Bash

Let’s get started with using Bash in your terminal.

πŸ–₯️ Getting Started with Bash

πŸ”‘ Accessing Bash

To begin, open a terminal on your system:

Check if you’re using Bash by running:

echo $SHELL

This should display /bin/bash or a similar path, confirming Bash is your shell.

To exit and end the session in terminal press CTRL+D or type:

exit

πŸ“ Basic Command Structure

Bash commands are text lines executed when you press Enter. A command typically includes:

Example:

ls -l /home

This lists the contents of the /home directory in a detailed format.

Tip: Press the Tab key to auto-complete commands, filenames, or directories, saving time and reducing errors.

πŸ“ Files and Directories

There are 3 types of file:

Bash operates within a hierarchical file system, starting from the root directory (/) to the file name. The pathname can be absolute or relative. The working directory is set to be home initially. Key commands for navigation include:

Visual Aid:

File System Hierarchy

A diagram of the UNIX file system hierarchy, showing the root and common directories.

~ Tilde Notation

The tilde (~) is a shortcut for your home directory. For example:

# Go to home directory
cd ~

# List files in Downloads
ls ~/Downloads

πŸ” Filenames, Wildcards, and Pathname Expansion

Wildcards are special characters that let you match multiple filenames, making commands more flexible.

Tip: Be cautious with wildcards in commands that can affect multiple files. Always verify before running destructive commands.

Pathname Expansion: Bash expands wildcards into pathname before executing the command, a process called pathname expansion. For example:

# To list all files in the directories /usr
ls /usr*

Brace Expansion

Brace expansion generates multiple strings from a pattern, useful for creating lists or filenames.

echo {a,b,c}.txt
# Outputs: a.txt b.txt c.txt

echo {1..5}
# Outputs: 1 2 3 4 5

echo ki{n,t,ng}s
# Outputs: kins kits kings

Tip: bash requires at least one unquoted comma to perform an expansion; otherwise, the word is left unchanged.

↔️ Input and Output

πŸ“Œ Key Ideas of UNIX I/O scheme:

Standard I/O

UNIX program has way of accepting input called standard input,producing output called standard output, and a single way of producing error messages called standard error.

UNIX utility programs are meant to perform a specific type of filtering operation on input text.

Utility and Purpose:

#Using cat to print the input given as output

cat
Hello World
# Output: Hello World

Use CTRL+D to stop the process in next line after pressing ENTER.

-> I/O Redirection

Bash allows you to redirect input and output to control data flow.

Redirection Operators

Tip: To redirect both stdout and stdin to a file, use:

cat < hello.txt > names.txt

Pipelines

Pipelines connect the output of one command to the input of another using the pipe operator (|).

# Lists only .txt files
ls | grep .txt

#View file listing one page at a time:
ls -l | more

#Sort numbers and print:
sort < numbers |more

⏳ Background Jobs

Background jobs let you run commands without tying up your terminal, freeing you to perform other tasks.

Running Background Jobs

Add an ampersand (&) to run a command in the background:

sleep 10 &  # Runs for 10 seconds in the background

Job Control Commands

Example:

sleep 10 &
jobs
fg %1  # Brings job 1 to foreground

Background I/O

Background jobs are connected to the terminal by default. If they try to read input, it may cause clutter on the screen. To avoid this, redirect I/O:

command input1.txt input2.txt > output.txt &

βš™οΈ Background Jobs and Priorities

Use nice to lower a job’s priority:

nice command

πŸ”£ Special Characters, Quoting, and Escaping

Special characters like *, |, and spaces have specific meanings in Bash. To use them literally, you need to quote or escape them.

Quoting :

echo 'Hello $USER'
# Outputs: Hello $USER
echo "Hello $USER"
# Outputs: Hello your_username

Backslash-Escaping

Use a backslash (\) before to escape a single special character meaning:

echo 5 \* 3 \> 15 is a invalid inequality.
# Outputs: 5 * 3 > 15 is a invalid inequality.
'\' #surround with quotes
\\  #backslash it

Quoting Quotation Marks

echo \"3 \* 3 \> 15\" is a invalid inequality.
# Output: "3 * 3 > 15" is a invalid inequality.
# Use backslash if no other special character
echo Hello everyone it\'s my Birthday

# Close and Reopen Quotes:
echo 'Hello everyone it'\''s my Birthday'
find [path] [string]
# Searches for filename starting from the current directory (.)
find . -name filename
# Quote the filename to match the string in each directory.
find . -name `*.c'

Continuing Lines

Continue long commands across multiple lines using a backslash or unclosed quotes:

echo "This is a \
long string"

echo 'This is a
long string'
# Outputs: This is a long string

πŸŽ›οΈ Control Keys

Control keys perform special actions:

ℹ️ Help Command

Get information on built-in commands:

help cd

For external commands or Unix/Linux commands:

ls --help

πŸ”§ Other Useful Commands

✍️ Command-Line Editing and History

Bash enhances productivity with command-line editing and history features.

Editing Modes

Bash defaults to emacs mode for editing commands but can switch to vi mode:

set -o vi  # Switch to vi mode
set -o emacs  # Switch back to emacs mode

Common emacs key bindings:

History List

Bash saves your commands in a history list, accessible via:

Example:

ls
# Press Up arrow to recall ls, edit, and run

Tip: Use CTRL-R to search history interactively. Type part of a command, and press CTRL-R to cycle through matches.

echo $HISTFILE

πŸ” 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 Here are some useful variables and what they do: