Shell 脚本是一个包含一系列 Shell 命令的文本文件,可以被 Shell 解释执行。它结合了命令、变量、控制结构和函数,用于自动化任务、系统管理和程序开发。
#!/bin/bash?这称为 shebang 或 hashbang,指定了执行该脚本的解释器路径。#!/bin/bash 表示使用 Bash shell 来执行脚本。其他常见形式包括 #!/bin/sh(使用系统默认 shell)或 #!/usr/bin/env bash(更灵活地查找 bash 路径)。
有三种主要方式:
- ./script.sh:需要脚本有可执行权限 (chmod +x script.sh)
- bash script.sh 或 sh script.sh:直接指定解释器
- source script.sh 或 . script.sh:在当前 shell 环境中执行(会影响当前环境变量)
var_name=value(注意等号两边不能有空格)$var_name 或 ${var_name}readonly var_name=valueunset var_name$0:脚本名称$1-$9:脚本参数$#:参数个数$* 和 $@:所有参数$?:上一条命令的退出状态$$:当前 shell 的进程 ID$!:最后一个后台进程的 PID使用 test 命令或 [ ] 或 [[ ]]:
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
常见条件:
- 字符串比较:=, !=, -z(为空), -n(非空)
- 数值比较:-eq, -ne, -gt, -lt, -ge, -le
- 文件测试:-e(存在), -f(普通文件), -d(目录), -r(可读), -w(可写), -x(可执行)
for 循环:
for var in list; do
commands
done
while 循环:
while [ condition ]; do
commands
done
until 循环:
until [ condition ]; do
commands
done
使用 read 命令:
read -p "Enter your name: " name
echo "Hello, $name"
选项:
- -p:提示信息
- -s:静默输入(适合密码)
- -t:超时时间
- -n:限制字符数
$1, $2, ..., $9$@ 或 $*$#shift(将参数向左移动一位)更高级的参数处理可以使用 getopts 或 getopt 命令。
定义:
function_name() {
commands
[return value]
}
使用:
function_name arg1 arg2
函数参数通过 $1, $2 等访问(不同于脚本参数),返回值通过 $? 获取。
if [ $? -ne 0 ]; then ...set -e:任何命令失败立即退出脚本set -o pipefail:管道中任何命令失败都视为失败trap 捕获信号:trap "commands" SIGNAL${#string}${string:position:length}${string/substring/replacement}${string#prefix}${string%suffix}${string^^}(转大写),${string,,}(转小写)$(( )):result=$((a + b))let:let "result = a + b"expr:result=$(expr $a + $b)bc(浮点运算):result=$(echo "scale=2; $a / $b" | bc)这些是 Shell 脚本中最常见和重要的概念和问题,掌握它们可以帮助你编写高效、健壮的 Shell 脚本。