导航菜单

Linux系统/Shell与脚本编程
课程进度 59% · 第6/9章6/9章 · 标签 1/3
1

Shell基础

Shell类型:

  • Bash:最常用的Shell
  • Zsh:功能强大的Shell
  • Fish:用户友好的Shell
  • Ksh:Korn Shell

Shell特性:

  • 命令解释器
  • 脚本编程语言
  • 环境变量管理
  • 命令历史记录
  • 命令补全

📖Shell脚本第一行通常是 #!/bin/bash,使用 chmod +x script.sh 添加执行权限,使用 ./script.sh 或 bash script.sh 运行脚本

脚本编程基础

bash
1
#!/bin/bash
2
# 变量定义
3
name="world"
4
 
5
# 条件判断
6
if [ "$name" = "world" ]; then
7
echo "Hello, $name!"
8
fi
9
 
10
# 循环
11
for i in {1..5}; do
12
echo $i
13
done
14
 
15
# 函数
16
greet() { echo "Hi, $1!"; }
17
greet Alice
2

常用特殊变量

bash
1
$0 # 脚本名称
2
$1-$9 # 位置参数
3
$# # 参数个数
4
$@ # 所有参数
5
$? # 上一条命令的返回值

文本处理命令

bash
1
# 文本搜索
2
grep 'pattern' file.txt
3
 
4
# 流编辑器
5
sed 's/old/new/g' file.txt
6
 
7
# 文本分析
8
awk '{print $1}' file.txt
9
 
10
# 字段提取
11
cut -d: -f1 /etc/passwd
12
 
13
# 排序
14
sort file.txt
15
 
16
# 去重
17
uniq file.txt

文件操作命令

bash
1
# 查找文件
2
find /home -name "*.sh"
3
 
4
# 参数传递
5
find . -type f | xargs wc -l
6
 
7
# 归档
8
tar -czvf archive.tar.gz dir/
9
 
10
# 压缩
11
gzip file.txt
12
 
13
# 同步
14
rsync -av src/ dest/

📖管道:command1 | command2,重定向:command > file,后台运行:command &,命令替换:$(command)

BashZshgrepsedawkfind