Shell脚本是一个包含一系列Shell命令的文本文件,可以被Shell解释执行。它结合了命令、变量、流程控制和函数,用于自动化系统管理任务或简化复杂操作。
创建:
#!/bin/bash
# 这是一个注释
echo "Hello World"
运行方式:
1. bash script.sh
2. 添加可执行权限后直接运行:chmod +x script.sh
然后 ./script.sh
定义变量:
name="John"
age=30
使用变量:
echo $name
echo ${name}
使用read
命令:
read -p "Enter your name: " username
echo "Hello, $username"
基本语法:
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
示例:
if [ $age -gt 18 ]; then
echo "Adult"
else
echo "Minor"
fi
字符串比较:
if [ "$str1" == "$str2" ]; then
if [ "$str1" != "$str2" ]; then
if [ -z "$str" ]; then # 检查是否为空
数字比较:
if [ $num1 -eq $num2 ]; then # 等于
if [ $num1 -ne $num2 ]; then # 不等于
if [ $num1 -gt $num2 ]; then # 大于
if [ $num1 -lt $num2 ]; then # 小于
for循环:
for i in {1..5}; do
echo "Number: $i"
done
while循环:
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
通过$1
, $2
, ..., $n
访问参数:
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"
定义:
function greet() {
echo "Hello, $1"
}
调用:
greet "Alice"
if [ -f "/path/to/file" ]; then # 检查文件
if [ -d "/path/to/dir" ]; then # 检查目录
if [ -e "/path/to/anything" ]; then # 检查是否存在
-x
选项:bash -x script.sh
set -x
开启调试,set +x
关闭调试echo
打印变量值>
覆盖重定向>>
追加重定向2>
错误重定向&>
标准和错误一起重定向示例:
command > output.txt
command 2> error.log
command &> both.log
$0
脚本名称$1-$9
位置参数$#
参数个数$@
所有参数$*
所有参数(作为一个单词)$?
上一个命令的退出状态$$
当前脚本的PID$!
最后一个后台进程的PID掌握这些基础知识后,你就可以编写功能强大的Shell脚本来自动化各种系统任务了!