1. What is a Shell and Shell Script?

In the Linux world, we interact with the system through the command line, and the Shell is the “middleman” of this interaction—it’s the interface program between the user and the Linux kernel. Think of it as a command interpreter that receives the commands you input and passes them to the system kernel for execution.

There are many common shells, such as bash (Bourne-Again Shell, the default in most Linux systems), sh (Bourne Shell), and zsh. A Shell script is a text file that contains a sequence of Linux commands, which are executed in bulk by the Shell interpreter to automate tasks.

For example: If you repeatedly need to perform actions like “backup files,” “clean logs,” or “check system status” every day, writing these steps in a Shell script allows you to run the script once to complete the task automatically, without manually typing commands each time.

2. Why Learn Shell Scripting?

Automation is the core value. Mastering Shell scripting helps you:
- Improve efficiency: Batch process files (e.g., renaming, format conversion) and schedule tasks (e.g., log cleaning).
- System management: Monitor server status (e.g., disk usage, CPU load) and automatically deploy services.
- Cross-platform reusability: Scripts are portable across different Linux systems with strong compatibility.

For beginners, Shell scripting has simple syntax and is easy to learn, making it a essential skill for Linux newcomers.

3. Writing Your First Shell Script: Hello World

Step 1: Prepare an editor
Linux systems have built-in text editors. Beginners are recommended to use nano (simpler) or vim (more powerful).
For nano: In the terminal, run nano hello.sh to open a blank editing window.

Step 2: Write the script content
Enter the following in the editor (note the purpose of each line):

#!/bin/bash
# This is a Shell script example
echo "Hello, Linux! 你好,世界!"
  • #!/bin/bash: Specifies the script uses the bash interpreter (must be the first line; otherwise, it may not be recognized).
  • Lines starting with # are comments and are not executed.
  • echo is the output command, printing text to the screen.

Step 3: Save and exit
- In nano, press Ctrl+O to save, then Enter to confirm the filename. Press Ctrl+X to exit.

Step 4: Add execution permissions
Scripts are by default “read-only.” Add executable permissions:

chmod +x hello.sh
  • chmod +x: Grants “executable” permissions to the file.

Step 5: Run the script
Execute in the terminal:

./hello.sh
  • Output: Hello, Linux! 你好,世界!
  • If you get “permission denied,” confirm Step 4 was executed correctly. If “file not found,” check the current directory (use pwd to view and ls to list files).

4. Basic Syntax and Common Commands in Shell Scripts

Variables: Variable names in Shell scripts start with a letter or underscore. Assign values without spaces around the equals sign.
Example:

name="小明"
age=20
echo "姓名:$name,年龄:$age"  # Use $ to prefix variables
  • Output: 姓名:小明,年龄:20

Common execution commands:
- echo "text": Output text to the screen (most commonly used).
- pwd: Show the current working directory.
- ls [directory]: List files in the specified directory (default: current directory).
- cd [path]: Change directory (e.g., cd ~ returns to the home directory).
- date: Show the current system time.

Comments:
- Single-line: # This is a single-line comment
- Multi-line:

  : '
  This is a multi-line comment
  You can write multiple lines
  '

5. Conditional Statements (if-else)

Use if-else to execute different code based on conditions:

if [ condition ]; then
    # Code to run if condition is true
elif [ another_condition ]; then
    # Code to run if the second condition is true
else
    # Code to run if all conditions are false
fi  # Close the if block (required)

Example 1: Check if a number is greater than 10

num=15
if [ $num -gt 10 ]; then  # -gt = "greater than"
    echo "$num is greater than 10"
elif [ $num -lt 5 ]; then  # -lt = "less than"
    echo "$num is less than 5"
else
    echo "$num is between 5 and 10"
fi
  • Output: 15 is greater than 10

Example 2: Check if a file exists

file="test.txt"
if [ -f $file ]; then  # -f checks if it's a regular file
    echo "$file exists"
else
    echo "$file does not exist"
fi

6. Loops (for/while)

Use loops to repeat code blocks.

For loop: Iterate over a list

# Print numbers 1 to 5
for i in {1..5}; do
    echo "Iteration $i"
done
  • Output:
  Iteration 1
  Iteration 2
  Iteration 3
  Iteration 4
  Iteration 5

While loop: Repeat while condition is true

# Calculate the sum of 1 to 5
sum=0
i=1
while [ $i -le 5 ]; do  # -le = "less than or equal to"
    sum=$((sum + i))
    i=$((i + 1))
done
echo "Sum from 1 to 5: $sum"  # Output: 15

7. Comprehensive Example: Automatic Backup Script

Requirement: Backup all .txt files in the current directory to a backup directory (create it if it doesn’t exist) and print the backup status.

#!/bin/bash
# Define variables
src_dir="."  # Current directory
backup_dir="./backup"
timestamp=$(date +%Y%m%d_%H%M%S)  # Timestamp for backup file prefix

# Create backup directory if it doesn't exist
if [ ! -d $backup_dir ]; then
    mkdir $backup_dir
    echo "Created backup directory: $backup_dir"
fi

# Backup all .txt files
txt_files=$(ls $src_dir/*.txt 2>/dev/null)  # Suppress errors if no .txt files
if [ -z "$txt_files" ]; then
    echo "No .txt files found in current directory. No backup needed."
else
    for file in $txt_files; do
        cp $file $backup_dir/$(basename $file)_$timestamp.txt
        echo "Backed up: $(basename $file)"
    done
    echo "Backup completed! Files are in: $backup_dir"
fi

Execution Steps:
1. Save as backup.sh, run chmod +x backup.sh
2. Execute: ./backup.sh

8. Advanced Recommendations

  • Learning Tools: Master tools like grep (text search), awk (text processing), and find (file search) to enhance script capabilities.
  • Practice: Start by modifying example scripts (e.g., adding parameters, adjusting conditions), then tackle complex scenarios (e.g., cron job scheduling with crontab).
  • Debugging: Add set -x at the beginning of your script to enable debugging mode and view execution details.

Shell scripting has a low entry barrier but requires practice to master. Start with simple repetitive tasks, and you’ll quickly see its ability to boost Linux operation efficiency!

Xiaoye