1. What is a Shell Script?

In the Linux system, we interact with the command line daily (e.g., using ls to list files, cd to change directories). The Shell is the system-provided “command interpreter” that receives user input commands and passes them to the system for execution.

A Shell script, however, is a text file containing a sequence of Linux commands, which the system executes automatically. For example, if you need to back up files daily or check server status, manually repeating commands is cumbersome—writing a script allows you to run it with a single click!

2. Why Learn Shell Scripting?

  • Automate Repetitive Tasks: E.g., scheduled log cleaning, batch file permission changes, or automatic program deployment.
  • Improve Efficiency: Replace manual operations and reduce errors (scripts execute commands in sequence, avoiding missed steps).
  • Essential for Server Management: Daily Linux server maintenance (monitoring, backups, troubleshooting) relies heavily on scripts, making it a foundational skill for system administrators/developers.

3. First Shell Script: Hello World

The first step in learning any programming language is to print “Hello World.” Let’s create the simplest Shell script!

Step 1: Create the Script File

Use an editor (e.g., nano or vim) to create a .sh file (.sh is the default extension for Shell scripts):

nano test.sh  # Use nano; if nano isn't installed, use vim test.sh

Step 2: Write the Script Content

Enter the following lines (each line is a command):

#!/bin/bash  # Specify the bash interpreter (must be first line)
echo "Hello, Linux Server!"  # Print a message
  • #!/bin/bash: Shebang line to specify the execution interpreter (e.g., use #!/bin/zsh for zsh).
  • echo: Output command, similar to Windows’ echo.

Step 3: Save and Exit

  • In nano: Press Ctrl+O to save (enter filename test.sh and press Enter), then Ctrl+X to exit.

Step 4: Add Execution Permissions

Shell scripts are readable/writable by default but not executable. Use chmod to grant execution rights:

chmod +x test.sh  # +x adds execute permission for the owner

Step 5: Run the Script

Execute the script file (use ./ for the current directory):

./test.sh

Output:

Hello, Linux Server!

4. Basic Shell Script Syntax

Variables and Assignment

Define variables in the format variable=value (no spaces around the equals sign!).

Example:

#!/bin/bash
name="Linux"  # Variable with string value
version=5     # Numeric variable
echo "Hello, $name! Version $version"  # Use $variable to call variables

Output:

Hello, Linux! Version 5

Common System Variables:
- $PATH: System command path (e.g., echo $PATH to view executable paths).
- $HOME: User home directory (e.g., echo $HOME shows /home/your_username).

Conditional Statements (if-else)

Use if to execute commands based on conditions:

if [ condition ]; then
  # Commands if condition is true
else
  # Commands if condition is false
fi  # Close the if block

Example: Check if a file exists

#!/bin/bash
file="test.txt"
if [ -f "$file" ]; then  # -f checks for a regular file
  echo "$file exists!"
else
  echo "$file not found. Creating..."
  touch "$file"  # Create an empty file
fi

Loops (for/while)

Loops repeat commands (e.g., iterating over files or repeated operations).

For Loop Example: Print 1 to 5

#!/bin/bash
for i in {1..5}; do  # {1..5} generates a sequence
  echo "Iteration $i"
done

While Loop Example: Sum 1 to 10

#!/bin/bash
sum=0
i=1
while [ $i -le 10 ]; do  # -le = less than or equal to
  sum=$((sum + i))  # Arithmetic within (( ))
  i=$((i + 1))
done
echo "Sum: $sum"  # Output: 55

5. Practical Example: Simple Server Monitoring Script

Check root partition disk usage and alert if over 80%:

#!/bin/bash
disk_usage=$(df -h | grep "/$" | awk '{print $5}' | sed 's/%//')  # Extract usage (remove %)

if [ $disk_usage -gt 80 ]; then  # -gt = greater than
  echo "Warning: Root partition usage is high! Current: $disk_usage%"
  # Optional: Send email (requires mailx)
  # echo "Clean up space!" | mail -s "Disk Alert" your@email.com
else
  echo "Root partition is healthy: $disk_usage%"
fi

Key Commands:
- df -h: View disk space (human-readable units).
- grep "/$": Filter root partition (ends with /).
- awk '{print $5}': Extract usage (5th column of df output).
- sed 's/%//': Remove the percent sign for numeric comparison.

6. Important Notes

  • Permissions: Always run chmod +x script.sh before executing a script.
  • Variable Assignment: No spaces around = (e.g., name="Linux" is correct; name = "Linux" is invalid).
  • Path Handling: Use ./script.sh for the current directory, or an absolute path like /home/user/script.sh.

7. Learning Resources

  • Practice: Manually run commands in the Linux terminal and modify scripts (variables, loops).
  • Tools: bash documentation (man bash), online editors (e.g., replit.com).
  • Advanced: Learn crontab for scheduling (e.g., crontab -e to run a script daily at 3 AM).

With Shell scripting, you can automate complex manual tasks and streamline Linux server management. Start with Hello World, then explore variables, conditions, and loops to build practical scripts!

Xiaoye