Skip to content

Shell Introduction

What is Shell?

Shell is the interface between the user and the Linux kernel. It receives commands entered by the user, interprets them, and passes them to the kernel for execution, then returns the results to the user.

┌──────────────────────────────────────────────────────────┐
│                        User                            │
│                         │                             │
│                         ▼                             │
│  ┌─────────────────────────────────────────────────┐    │
│  │                    Shell                         │    │
│  │   • Command interpreter                      │    │
│  │   • Script programming environment            │    │
│  │   • User interaction interface                │    │
│  └─────────────────────────────────────────────────┘    │
│                         │                             │
│                         ▼                             │
│  ┌─────────────────────────────────────────────────┐    │
│  │                  Linux Kernel                   │    │
│  │   • Process management                     │    │
│  │   • Memory management                      │    │
│  │   • File system                           │    │
│  │   • Device drivers                        │    │
│  └─────────────────────────────────────────────────┘    │
│                         │                             │
│                         ▼                             │
│                      Hardware                             │
└──────────────────────────────────────────────────────────┘

Shell Functions

1. Command Interpretation

Shell reads and executes user-entered commands:

bash
$ ls -la /home
# Shell parses this command, calls the ls program, and passes the arguments -la and /home

2. Script Programming

Shell is a script programming language that can write automation scripts:

bash
#!/bin/bash
for file in *.txt; do
    echo "Processing file: $file"
done

3. Environment Management

Shell manages environment variables and working environment:

bash
$ export PATH=$PATH:/new/path
$ echo $HOME

4. Input/Output Redirection

Shell can redirect command input and output:

bash
$ command > output.txt     # Output redirection
$ command < input.txt      # Input redirection
$ command1 | command2      # Pipe

5. Job Control

Shell can manage background processes:

bash
$ command &                # Run in background
$ jobs                     # View jobs
$ fg                       # Bring to foreground

Common Shells

Bash (Bourne Again Shell)

The most popular Shell, the default Shell for most Linux distributions.

Features

  • Part of the GNU project
  • Compatible with Bourne Shell (sh)
  • Rich features: command completion, history, aliases
  • Powerful scripting capabilities
bash
# Check if using Bash
$ echo $BASH_VERSION
5.1.16(1)-release

Zsh (Z Shell)

A more feature-rich Shell, the default Shell for macOS.

Features

  • Powerful auto-completion
  • Theme and plugin support (Oh My Zsh)
  • Spell correction
  • Shared history
bash
# Install Zsh
$ sudo apt install zsh

# Set as default Shell
$ chsh -s /bin/zsh

Fish (Friendly Interactive Shell)

A user-friendly modern Shell.

Features

  • Out-of-the-box syntax highlighting
  • Intelligent auto-completion
  • Web-based configuration
  • Not POSIX compatible
bash
# Install Fish
$ sudo apt install fish

# Run Fish
$ fish

Other Shells

ShellDescription
sh (Bourne Shell)The earliest Unix Shell
csh (C Shell)C-like syntax
tcshEnhanced version of csh
ksh (Korn Shell)Commonly used in commercial Unix
dashDefault Shell for Debian system scripts

Viewing and Switching Shells

View Current Shell

bash
# Method 1: View $SHELL variable
$ echo $SHELL
/bin/bash

# Method 2: View current process
$ ps -p $$
  PID TTY          TIME CMD
 1234 pts/0    00:00:00 bash

# Method 3: View $0
$ echo $0
-bash

View Available Shells

bash
$ cat /etc/shells
/bin/sh
/bin/bash
/bin/zsh
/usr/bin/zsh
/bin/fish

Temporary Shell Switch

bash
# Start Zsh
$ zsh

# Start Fish
$ fish

# Exit back to original Shell
$ exit

Change Default Shell

bash
# Use chsh command
$ chsh -s /bin/zsh

# Or edit /etc/passwd (requires root)
$ sudo usermod -s /bin/zsh username

Bash Configuration Files

Bash uses multiple configuration files that are loaded in different scenarios.

Configuration File Overview

┌─────────────────────────────────────────────────────────────┐
│                    Shell Startup Type                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   Login Shell                      Non-Login Shell        │
│   (Login Shell)                   (Non-login Shell)       │
│        │                                │               │
│        ▼                                ▼               │
│   /etc/profile                    /etc/bash.bashrc          │
│        │                                │               │
│        ▼                                ▼               │
│   ~/.bash_profile                 ~/.bashrc               │
│   or ~/.bash_login                                          │
│   or ~/.profile                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Login Shell vs Non-Login Shell

Login Shell

  • Starts when user logs into the system (TTY login, SSH login)
  • Executes /etc/profile and ~/.bash_profile

Non-Login Shell

  • Starts when opening a terminal emulator
  • Executes /etc/bash.bashrc and ~/.bashrc
bash
# Check if it's a login Shell
$ shopt -q login_shell && echo "Login Shell" || echo "Non-login Shell"

# Force login Shell
$ bash --login
$ bash -l

Main Configuration Files

/etc/profile (System-level, at login)

bash
# System-wide environment variable settings
# Executed when all users log in

~/.bash_profile (User-level, at login)

bash
# User's login configuration
# Usually contains:
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

~/.bashrc (User-level, each startup)

bash
# User's Shell configuration
# Aliases, functions, prompts, etc.

# Aliases
alias ll='ls -la'
alias grep='grep --color=auto'

# Environment variables
export EDITOR=vim

# Custom functions
mkcd() {
    mkdir -p "$1" && cd "$1"
}

# Prompt
PS1='\u@\h:\w\$ '

~/.bash_logout (at exit)

bash
# Commands to execute on logout
# For example, cleaning temporary files

Loading Configuration Files

bash
# Reload .bashrc
$ source ~/.bashrc
$ . ~/.bashrc

# Reload .profile
$ source ~/.profile

Shell Prompt

PS1 - Main Prompt

bash
# View current PS1
$ echo $PS1
\u@\h:\w\$

# Customize prompt
$ PS1="[\t] \u@\h:\w\$ "
[10:30:00] maxwell@ubuntu:~$

Special Characters

CharacterMeaning
\uUsername
\hHostname
\HFull hostname
\wCurrent directory
\WCurrent directory name (without path)
\dDate
\tTime (24-hour)
\TTime (12-hour)
\nNewline
\$Prompt (regular user $, root #)
\[...\]Non-printing character wrapper (for colors)

Colored Prompt

bash
# Color codes
# \e[color code]m start, \e[0m end

# Example: Green username, blue path
PS1='\[\e[32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '

Common Color Codes

CodeColor
30Black
31Red
32Green
33Yellow
34Blue
35Magenta
36Cyan
37White

PS2 - Continuation Prompt

bash
# Displayed when command is incomplete
$ echo "hello
> world"

PS3 and PS4

bash
# PS3 - Prompt for select statement
# PS4 - Prompt for debug mode

Bash Features

Command History

bash
# View history
$ history

# History configuration
HISTSIZE=1000           # Number of commands saved in memory
HISTFILESIZE=2000       # Number of commands saved in history file
HISTCONTROL=ignoreboth  # Ignore duplicate and space-prefixed commands
HISTIGNORE="ls:cd:pwd"  # Ignore specific commands

Command Completion

bash
# Tab completion for files and commands
$ cd Doc<Tab>
$ cd Documents/

# Install enhanced completion
$ sudo apt install bash-completion

Aliases

bash
# Define alias
$ alias ll='ls -la'

# View aliases
$ alias

# Delete alias
$ unalias ll

# Temporarily skip alias
$ \ls
$ command ls

Command Types

bash
# Built-in commands: Commands built into Shell
$ type cd
cd is a shell builtin

# External commands: Independent executable files
$ type ls
ls is /usr/bin/ls

# Aliases
$ type ll
ll is aliased to 'ls -la'

# Functions
$ type mkcd
mkcd is a function

Oh My Bash

Oh My Bash is a Bash configuration framework that provides themes and plugins.

Installation

bash
$ bash -c "$(curl -fsSL https://raw.githubusercontent.com/ohmybash/oh-my-bash/master/tools/install.sh)"

Configuration

Edit ~/.bashrc:

bash
# Theme
OSH_THEME="powerline"

# Plugins
plugins=(git bashmarks)

Summary

This chapter introduced the basic concepts of Shell:

  • Shell's role: Command interpretation, script programming, environment management
  • Common Shells: Bash, Zsh, Fish
  • Configuration files: .bashrc, .bash_profile, etc.
  • Prompt customization: PS1 and color settings
  • Bash features: History, completion, aliases

Shell is a core tool in Linux; understanding it deeply will greatly improve your work efficiency. Next, we'll learn about input/output redirection.


Previous chapter: File Search

Next chapter: Input/Output Redirection

Content is for learning and research only.