1. Command Line Overview
Command Line Interface (CLI) is one of the main ways for users to interact with Linux systems. Through the command line, users can execute various system commands, manage files and directories, run programs, configure systems, and more. Although graphical interfaces are becoming more popular, the command line remains the core tool for Linux system administration because it is more powerful, flexible, and efficient.
1.1 Advantages of Command Line
- Powerful Functionality: The command line provides powerful functionality and flexibility that graphical interfaces cannot match.
- Efficient Operations: Proficient use of the command line can greatly improve work efficiency, especially for repetitive tasks.
- Remote managementment: Through protocols like SSH, Linux systems can be remotely managed from anywhere.
- Automation: Commands can be combined through scripts to achieve task automation.
- Low Resource Usage: The command line interface occupies fewer system resources, suitable for use in resource-limited environments.
- Consistency: The command line is basically consistent across different Linux distributions, learn once and use on multiple systems.
2. Shell Introduction
Shell is a command line interpreter that receives commands input by users and then executes corresponding operations. In Linux, there are multiple Shells to choose from, each with its own characteristics and functions.
2.1 Common Shells
2.1.1 Bash (Bourne Again Shell)
Bash is the default Shell for most Linux distributions. It is an enhanced version of the Bourne Shell, providing more features and functionalities.
- supports command history
- supports command completion
- supports aliases
- supports pipes and redirection
- supports script programming
2.1.2 Zsh (Z Shell)
Zsh is a powerful Shell that combines the advantages of Bash, Ksh, and Tcsh, providing more advanced features.
- More powerful command completion
- Better theme support
- More flexible configuration options
- supports spelling correction
2.1.3 Fish (Friendly Interactive Shell)
Fish is a user-friendly Shell that provides an intuitive interface and powerful auto-completion features.
- Automatic syntax highlighting
- Intelligent auto-completion
- Web-based configuration interface
- Friendly error prompts
2.2 View Current Shell
# View current Shell echo $SHELL # View available Shells in the system cat /etc/shells
3. Basic Commands
Linux systems provide a large number of commands. Here are some of the most commonly used basic commands:
3.1 File and Directory Operation Commands
# List directory contents ls ls -la # Show detailed information ls -lh # Show in human-readable format ls -R # List recursively # Change directory cd /path/to/directory cd ~ # Change to home directory cd .. # Change to parent directory # Create directory mkdir directory mkdir -p dir1/dir2/dir3 # Create nested directories # Delete file or directory rm file.txt rm -f file.txt # Force delete rm -r directory # Recursively delete directory # Copy file or directory cp source.txt destination.txt cp -r source_dir destination_dir # Move or rename file/directory mv oldname.txt newname.txt mv file.txt /path/to/directory/
3.2 File Content Viewing Commands
# View file content cat file.txt # View with pagination less file.txt more file.txt # View file head head file.txt head -n 10 file.txt # View first 10 lines # View file tail tail file.txt tail -n 10 file.txt # View last 10 lines tail -f file.txt # View file changes in real-time # View file type file file.txt # Search file content grep "pattern" file.txt grep -r "pattern" directory/ # Recursive search grep -i "pattern" file.txt # Ignore case grep -n "pattern" file.txt # Show line numbers
3.3 System Information Commands
# View system information uname -a # View kernel version uname -r # View system distribution information cat /etc/os-release lsb_release -a # View CPU information cat /proc/cpuinfo lscpu # View memory information free -h # View disk space df -h # View directory size du -h directory du -sh directory # View total size # View system load uptime w # View current logged-in users who whoami # View system time date cal
3.4 Network Commands
# View network interfaces ifconfig ip addr # View routing table route -n ip route # Test network connection ping google.com # View network connections netstat -tuln ss -tuln # View DNS configuration cat /etc/resolv.conf # View hostname hostname echo $HOSTNAME # View local hostname resolution cat /etc/hosts # Download file wget https://example.com/file.txt curl -O https://example.com/file.txt
4. Command Line Tips
Mastering some command line tips can greatly improve work efficiency:
4.1 Command History
# View command history history # Use up/down arrows to browse history commands # Press Ctrl+R to search history commands # Execute the nth command in history !n # Execute previous command !! # Execute previous command starting with specific string !string # Clear command history history -c # Save command history to file history > history.txt
4.2 Command Completion
Using the Tab key can automatically complete commands, filenames, and directory names. This is a very useful feature that saves time and reduces input errors.
# complete command ls -la /u[TAB] # Will complete to /usr # complete filename cat doc[TAB] # Will complete to document.txt (if exists) # Double tap Tab to show all possible completion options ls /u[TAB][TAB] # Will show /usr, /var, etc.
4.3 Command Aliases
You can create aliases for frequently used commands to simplify command input:
# Create temporary alias alias ll='ls -la' alias la='ls -a' alias cls='clear' # View all aliases alias # Remove alias unalias ll # Create permanent alias (edit ~/.bashrc file) echo "alias ll='ls -la'" >> ~/.bashrc source ~/.bashrc # Make alias effective
4.4 Working Directory Navigation
# View current working directory pwd # Quick directory switch cd - # Jump to previous directory cd $OLDPWD # Use pushd and popd to manage directory stack pushd /path/to/dir1 pushd /path/to/dir2 popd popd
4.5 Command Line Editing
Bash provides multiple command line editing shortcuts:
- Ctrl+A: Move to beginning of command line
- Ctrl+E: Move to end of command line
- Ctrl+U: Delete all characters before cursor
- Ctrl+K: Delete all characters after cursor
- Ctrl+W: Delete one word before cursor
- Ctrl+L: Clear screen
- Ctrl+C: Interrupt current command
- Ctrl+D: Exit current Shell or indicate EOF
- Ctrl+Z: Pause current command, put in background
5. Pipes and Redirection
Pipes and redirection are very powerful features in the Linux command line. They allow you to connect commands together to achieve more complex functions.
5.1 Redirection
# Redirect command output to file (overwrite) echo "Hello World" > file.txt # Append command output to file echo "Hello Again" >> file.txt # Redirect standard error to file error_command 2> error.txt # Redirect both standard output and standard error to file command > output.txt 2>&1 command &> output.txt # Redirect input cat < input.txt # Null device (/dev/null) - used to discard output command > /dev/null # Here Document cat > file.txt << EOF Line 1 Line 2 Line 3 EOF # Here String cat <<< "Hello World"
5.2 Pipes
Pipes (|) are used to pass the output of one command as the input to another command:
# Pipe example ls -la | grep "txt" # List all .txt files # Multiple pipe combination ps aux | grep "python" | wc -l # Count Python processes # Common pipe commands ls -la | sort -k 5 -nr # Sort by file size # Use xargs to pass pipe output as command arguments find . -name "*.txt" | xargs cat # View all .txt file contents find . -name "*.tmp" | xargs rm # Delete all .tmp files # Use tee command to output to both terminal and file ls -la | tee output.txt
6. Environment Variables
Environment variables are variables used to store configuration information in the operating system. They have an important impact on system operation and the user's working environment.
6.1 View Environment Variables
# View all environment variables env export # View specific environment variables echo $HOME echo $PATH echo $USER echo $SHELL # Search environment variables env | grep "PATH" set | grep "HOME"
6.2 Set Environment Variables
# Set temporary environment variable MY_VAR="Hello" export MY_VAR # Set and export in the same line export MY_VAR="Hello" # Use environment variable echo $MY_VAR # Unset environment variable unset MY_VAR # Set permanent environment variable (edit ~/.bashrc file) echo "export MY_VAR='Hello'" >> ~/.bashrc source ~/.bashrc # Or edit /etc/profile file (effective for all users) sudo echo "export MY_VAR='Hello'" >> /etc/profile source /etc/profile
6.3 Important Environment Variables
- HOME: User home directory
- PATH: Command search path
- USER: Current username
- SHELL: Current Shell
- LANG: Language environment
- PS1: Command prompt
- OLDPWD: Previous working directory
- PWD: Current working directory
- TERM: Terminal type
7. Shell Script Basics
Shell script is a simple programming language that allows you to combine multiple commands together to achieve automated tasks.
7.1 Creating and Running Shell Scripts
# Create Shell script file cat > hello.sh << 'EOF' #!/bin/bash # This is a simple Shell script echo "Hello, World!" echo "Current date: $(date)" echo "Current user: $USER" EOF # Add execute permission to script chmod +x hello.sh # Run script ./hello.sh # Or run with bash command bash hello.sh # Or run with sh command sh hello.sh
7.2 Shell Script Syntax
7.2.1 Variables
#!/bin/bash
# Define variables
name="Linux"
age=10
# Use variables
echo "Hello, $name!"
echo "You are $age years old."
# Command substitution
current_dir=$(pwd)
echo "Current directory: $current_dir"
# Arithmetic operation
num1=10
num2=5
sum=$((num1 + num2))
echo "Sum: $sum"
# String operation
greeting="Hello, World!"
echo "Length: ${#greeting}"
echo "Substring: ${greeting:7:5}"
7.2.2 Conditional Statements
#!/bin/bash
# if statement
if [ $1 -gt 10 ]; then
echo "Number is greater than 10"
elif [ $1 -eq 10 ]; then
echo "Number is equal to 10"
else
echo "Number is less than 10"
fi
# File test
if [ -f "file.txt" ]; then
echo "File exists"
else
echo "File does not exist"
fi
# String comparison
if [ "$USER" = "root" ]; then
echo "You are root user"
else
echo "You are not root user"
fi
7.2.3 Loop Statements
#!/bin/bash
# for loop
for i in {1..5}; do
echo "Number: $i"
done
# Iterate files
for file in *.txt; do
echo "File: $file"
done
# while loop
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
# until loop
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
7.2.4 Functions
#!/bin/bash
# Define function
greet() {
echo "Hello, $1!"
}
# Call function
greet "Linux"
# Function with return value
add() {
local sum=$(( $1 + $2 ))
echo $sum
}
# Use function return value
result=$(add 10 20)
echo "Result: $result"
# Function arguments
print_args() {
echo "Number of arguments: $#"
echo "All arguments: $@"
echo "First argument: $1"
echo "Second argument: $2"
}
print_args 1 2 3 4 5
8. Practice Case: System Monitoring Script
8.1 Case Objective
Create a system monitoring script that regularly checks the system's CPU using, memory using, disk space, and network connections, and saves the results to a log file.
8.2 Implementation Steps
8.2.1 Create Monitoring Script
#!/bin/bash
# System monitoring script
# Define log file
LOG_FILE="/var/log/system_monitor.log"
# Create log directory
mkdir -p /var/log
# Define monitoring function
monitor_system() {
# Get current time
current_time=$(date "%Y-%m-%d %H:%M:%S")
# Write log header
echo "========================================" >> $LOG_FILE
echo "System Monitor - $current_time" >> $LOG_FILE
echo "========================================" >> $LOG_FILE
# Monitor CPU using
echo "CPU Usage:" >> $LOG_FILE
top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}' >> $LOG_FILE
# Monitor memory using
echo "Memory Usage:" >> $LOG_FILE
free -h >> $LOG_FILE
# Monitor disk space
echo "Disk Usage:" >> $LOG_FILE
df -h >> $LOG_FILE
# Monitor network connections
echo "Network Connections:" >> $LOG_FILE
netstat -tuln | grep LISTEN >> $LOG_FILE
# Monitor system load
echo "System Load:" >> $LOG_FILE
uptime >> $LOG_FILE
# Write log footer
echo "========================================" >> $LOG_FILE
echo "" >> $LOG_FILE
}
# Execute monitoring
monitor_system
# Output prompt
echo "System monitoring completed. Log saved to $LOG_FILE"
8.2.2 Add Execute Permission to Script
chmod +x system_monitor.sh
8.2.3 Run Script
./system_monitor.sh
8.2.4 Set Up Scheduled Execution
Use cron to set up scheduled execution of the script:
# Edit crontab file crontab -e # Add the following line (execute every hour) 0 * * * * /path/to/system_monitor.sh # View crontab tasks crontab -l
9. Interactive Exercises
Exercise 1: Command Line Navigation
Perform the following operations:
- 1. Switch to the root directory and view all directories under the root directory.
- 2. Enter the /etc directory and view the configuration files there.
- 3. Enter the /var/log directory and view the system log files.
- 4. Return to the user's home directory and create a directory named test.
- 5. Create a file named file.txt in the test directory and write "Hello Linux" into it.
- 6. View the content of file.txt.
- 7. Delete the test directory and its contents.
Exercise 2: Command Combination
Use pipes and redirection to combine commands to complete the following tasks:
- 1. Find all files ending with .conf in the system and save the results to conf_files.txt.
- 2. Count how many directories ending with .d are in the /etc directory.
- 3. View the run processes in the system, filter out processes containing "ssh", and save the results to ssh_processes.txt.
- 4. View the last 100 lines of the /var/log/syslog file, filter out lines containing "error", and save the results to error_logs.txt.
Exercise 3: Create Backup Script
Create a backup script with the following functions:
- 1. Backup all files in the user's home directory to a specified backup directory.
- 2. Name the backup file with the current date in the format backup_YYYY-MM-DD.tar.gz.
- 3. Check if there is enough space in the backup directory, and prompt the user if there is not enough space.
- 4. After backup is completed, display the size and location of the backup file.
- 5. Add execute permission and run the script for testing.