Mastering Linux Shell Scripting: A Complete Hands‑On Guide from Basics to Pro
This article walks readers through the fundamentals of Linux shell scripting—explaining what a script is, why automation matters, core syntax, variables, conditionals, loops, functions, real‑world examples, debugging techniques, and best‑practice recommendations—so they can write reliable Bash scripts from scratch and advance to more complex automation tasks.
What is a Shell script and why learn it?
A Shell script is a text file containing a series of Linux commands that can be executed automatically after giving the file execute permission. The author likens it to a cooking recipe: the script lists steps such as creating directories, copying files, changing permissions, and starting services, allowing the same sequence to be run without manual input.
Automation saves time: performing routine tasks like checking disk usage, monitoring services, backing up databases, and cleaning logs can consume up to 30 minutes daily (≈180 hours per year). Writing a script that runs automatically can reclaim that time, reduce human error, improve reusability, provide documentation, and even increase a sysadmin’s market value.
Shell script basics
The first script, hello.sh, demonstrates the shebang line ( #!/bin/bash), comments, and the echo command. The author highlights three execution methods:
Give the script execute permission and run it (creates a subshell).
Invoke the script with bash script.sh (also a subshell).
Source the script with source script.sh (runs in the current shell, preserving variables).
Variables
Variables are defined without spaces around the equals sign, e.g., NAME="运维小哥" and AGE=25. The author stresses using the ${NAME} syntax to avoid ambiguity. Variable types covered include local, environment, positional parameters ($0, $1, $@, $#), and special variables ($?, $$).
Advanced operations such as string length ( echo ${#NAME}), substring removal ( echo ${FILE%.gz}), replacement ( echo ${TEXT/hello/hi}), and default values ( echo ${NAME:-默认值}) are illustrated.
Conditional statements
Conditionals rely on the test command or [ ] syntax. File tests use flags like -e, -f, -d, etc. Numeric comparisons use -eq, -ne, -gt, -ge, -lt, -le. The more powerful [[ ]] form supports regular expressions, e.g., if [[ "$FILE" =~ \.txt$ ]]; then …. Full if and case structures are shown.
Loops
Common loops include for (iterating over lists, files, or using C‑style syntax) and while (reading a file line‑by‑line). Loop control statements break and continue are explained.
Functions
Functions can be defined as func_name() { … } or with the function keyword. Parameters are accessed via $1, $2, etc., and the local keyword limits variable scope. An example adds two numbers and returns the result.
Practical scripts
Four ready‑to‑use scripts are provided:
Server resource monitor ( monitor.sh) that logs CPU and disk usage.
MySQL backup script ( mysql_backup.sh) that dumps each database and compresses the output.
Service guard ( service_guard.sh) that checks and restarts essential services.
Server initialization ( init_server.sh) that sets timezone, installs tools, and disables SELinux.
Log rotation script ( log_rotate.sh) for Nginx logs.
Debugging and best practices
Enable tracing with set -x, check exit codes via $?, and adopt strict mode ( set -euo pipefail) to abort on errors. Always quote variables, use local inside functions, and avoid hard‑coding passwords—prefer reading from secure files or environment variables.
Input validation examples show how to ensure a port number is numeric before proceeding.
Summary and next steps
The author recaps core topics—syntax, conditionals, loops, functions, string handling, arrays, and debugging—and suggests a learning path: practice with sed / awk, explore Expect for interactive automation, then move to Python‑based tools like Ansible or SaltStack. Recommended resources include the book "Linux Command Line and Shell Scripting Bible", the ShellCheck tool, and explainshell.com.
With consistent practice, readers can master shell scripting, save substantial time, and automate repetitive tasks effectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
AI Agent Super App
AI agent applications, installation, large-model testing, computer fundamentals, IT operations and maintenance exchange, network technology exchange, Linux learning
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
