Master Shell Scripting: From Basics to Advanced Tricks
This comprehensive guide walks you through the fundamentals of shell and shell scripting, covering common shells, script creation, shebang usage, variable handling, environment variables, string manipulation, and practical examples to boost your Linux automation skills.
What Is a Shell
Shellis a layer that wraps the operating system core, providing a direct interface for users to interact with the system; it interprets user input and returns output to the screen.
It is one of the main ways users communicate with the system, interpreting commands and displaying results.
The Shell explains user commands and outputs results, whether via command‑line or graphical interfaces.
What Is a Shell Script
A Shell script is a file that contains a series of Linux commands and control statements. When executed, the commands run non‑interactively.
Windows uses *.bat batch files.
Linux commonly uses *.sh scripts.
Shell Script Rules
Shell scripts are usually edited with vim and consist of Linux commands, Bash directives, logic control statements, and comments.
First Shell Script
# vim test1.sh
# cat test1.sh
# 第一个 shell 脚本 这是注释
#!/bin/bash
echo "hello world!"Run it with:
# bash test1.sh
hello world!Shebang
The shebang ( #!) on the first line tells the system which interpreter to use, e.g., #!/bin/bash invokes the Bash interpreter.
If no shebang is specified, the current shell ( $SHELL) is used.
If the interpreter path is missing or not executable, an error occurs.
Common Ways to Execute Scripts
1. Use bash script.sh or sh script.sh (no execute permission needed).
$ sh helloworld.sh
Helloworld2. Make the script executable ( chmod +x script.sh) and run it directly:
$ ./helloworld.sh
HelloworldThe first method runs the script via the Bash interpreter, while the second runs the script itself, requiring execute permission.
Shell Variables
Variables are defined without spaces, e.g., name="zfox". Bash treats all variables as strings by default.
name="zfox"
# Access
echo ${name}
# or
echo $nameVariable naming rules:
Use letters, numbers, and underscores; cannot start with a number.
Case‑sensitive.
System Variables
Common system variables include HOME, PWD, SHELL, USER, etc.
$ echo $HOME
/home/zfoxList all variables with set or env.
Custom Variables
Define with var=value, delete with unset var, make read‑only with readonly var.
Single vs Double Quotes
Single quotes prevent variable expansion; double quotes allow it. Backticks (or $(...)) capture command output.
# name="奥里给"
# echo '${name}'
${name}
# double quotes
# echo "${name}"
zfox带你学bashSpecial Variables
$?– exit status (0 = success). $# – number of positional parameters. $* – all parameters as a single string. $@ – all parameters as separate strings.
Environment Variable Management
Exported variables define the shell’s runtime environment. User‑specific files ( ~/.bash_profile, ~/.bashrc) and global files ( /etc/profile, /etc/bashrc) store them.
Commands to view or modify: set – show all variables. env – show environment variables. declare – list variables. export – set/export a variable.
Read‑Only Variables
# readonly name="super"
# name="changed" # will fail
-bash: name: readonly variableEnvironment Variable Initialization Order
Shell Substring Operations
${var} # value
${#var} # length
${var:offset} # from offset
${var:offset:length} # length chars
${var#word} # remove shortest prefix match
${var##word} # remove longest prefix match
${var%word} # remove shortest suffix match
${var%%word} # remove longest suffix match
${var/pattern/repl} # replace first match
${var//pattern/repl} # replace all matchesExample:
name="yuchao180"
echo ${#name} # 9
echo ${name:3} # hao180
echo ${name:2:4} # chaoString Replacement
str="Hello,man,i am your brother."
echo ${str/man/boy} # Hello,boy,i am your brother.
echo ${str//o/O} # HellO,man,i am yOur brOther.Batch Rename Example
# Create sample files
touch chaochao_{1..5}_finished.jpg
touch chaochao_{1..5}_finished.png
# Rename to remove "_finished"
for file in *finished.jpg; do
mv "$file" "${file//_finished/}"
doneConclusion
These notes cover the essentials of Shell scripting, from basic concepts to practical tricks, helping you automate tasks efficiently on Linux.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
