从入门到精通的命令行艺术
Shell脚本是一种为shell编写的脚本程序,它可以将一系列命令组合在一起,实现自动化任务、系统管理和程序开发等功能。Shell脚本在Unix/Linux系统中广泛应用,是系统管理员和开发人员的必备技能。
.sh作为文件扩展名,但这并不是必须的。
让我们从一个简单的"Hello World"脚本开始:
#!/bin/bash
# 这是我的第一个Shell脚本
echo "Hello World!"
要运行这个脚本,你需要:
hello.shchmod +x hello.sh./hello.sh#!/bin/bash称为shebang,它指定了用来执行脚本的解释器。
Shell脚本中的变量不需要声明,直接赋值即可:
#!/bin/bash
name="John Doe"
age=30
echo "My name is $name and I am $age years old."
$0 - 脚本名称$1-$9 - 脚本参数$# - 参数个数$* - 所有参数$? - 上一个命令的退出状态$$ - 当前脚本的进程IDShell脚本使用if语句进行条件判断:
#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 10 ]; then
echo "The number is greater than 10"
elif [ $num -eq 10 ]; then
echo "The number is equal to 10"
else
echo "The number is less than 10"
fi
-eq, -ne, -gt, -lt, -ge, -le=, !=, -z (空字符串)-e (存在), -f (普通文件), -d (目录)#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
# 或者使用序列
for i in {1..5}; do
echo "Number: $i"
done
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
#!/bin/bash
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
Shell脚本中可以定义函数来组织代码:
#!/bin/bash
# 定义函数
greet() {
local name=$1
echo "Hello, $name!"
}
# 调用函数
greet "Alice"
greet "Bob"
local关键字可以声明局部变量,否则变量默认为全局的。
#!/bin/bash
# 备份目录脚本
backup_dir="/backup"
source_dir="/var/www"
if [ ! -d "$backup_dir" ]; then
mkdir -p "$backup_dir"
fi
backup_file="backup_$(date +%Y%m%d_%H%M%S).tar.gz"
echo "Starting backup..."
tar -czf "$backup_dir/$backup_file" "$source_dir"
if [ $? -eq 0 ]; then
echo "Backup completed successfully: $backup_file"
else
echo "Backup failed!" >&2
exit 1
fi
#!/bin/bash
# 系统监控脚本
echo "===== System Information ====="
echo "Hostname: $(hostname)"
echo "Uptime: $(uptime -p)"
echo "Load Average: $(uptime | awk -F'load average: ' '{print $2}')"
echo "Memory Usage: $(free -h | awk '/Mem/{print $3 "/" $2}')"
echo "Disk Usage:"
df -h | grep -v "tmpfs"
-x选项调试脚本:bash -x script.shset -x开启调试,set +x关闭调试trap捕获信号:trap 'echo "Error on line $LINENO"' ERRbash -n script.sh要深入学习Shell脚本编程,可以参考以下资源:
man bash实践是学习Shell脚本的最佳方式,尝试编写自己的脚本来解决实际问题!
下载示例脚本 更多教程