# Shell 快速开始
# Shell简介
Shell是用户与操作系统交互的接口,通过命令行方式执行各种操作。常见的Shell包括:
- Bash (Bourne Again Shell)
- Zsh
- Fish
# 基本命令
# 文件和目录操作
# 显示当前目录
pwd
# 列出文件和目录
ls
ls -l # 详细信息
ls -a # 显示隐藏文件
# 创建目录
mkdir mydir
# 创建文件
touch file.txt
# 复制文件
cp source.txt dest.txt
# 移动/重命名文件
mv old.txt new.txt
# 删除文件和目录
rm file.txt
rm -r directory # 递归删除目录
# 文件内容操作
# 查看文件内容
cat file.txt
less file.txt
head -n 5 file.txt # 显示前5行
tail -n 5 file.txt # 显示后5行
# 文本搜索
grep "pattern" file.txt
grep -r "pattern" directory # 递归搜索
# 文本编辑
echo "Hello" > file.txt # 覆盖写入
echo "World" >> file.txt # 追加写入
# 编写Shell脚本
# 第一个脚本
#!/bin/bash
# hello.sh
echo "Hello, Shell!"
运行脚本:
chmod +x hello.sh # 添加执行权限
./hello.sh # 运行脚本
# 变量
# 定义变量
name="Shell"
age=25
# 使用变量
echo "Name: $name"
echo "Age: $age"
# 命令结果赋值
current_date=$(date)
echo "Current date: $current_date"
# 条件判断
#!/bin/bash
# if条件
if [ $age -ge 18 ]; then
echo "成年人"
else
echo "未成年"
fi
# 文件判断
if [ -f "file.txt" ]; then
echo "文件存在"
fi
# 字符串比较
if [ "$name" = "Shell" ]; then
echo "Hello Shell"
fi
# 循环
# for循环
for i in 1 2 3 4 5; do
echo $i
done
# while循环
count=0
while [ $count -lt 3 ]; do
echo $count
count=$((count + 1))
done
# 函数
# 定义函数
greet() {
echo "Hello, $1!"
}
# 调用函数
greet "Shell"
# 实用技巧
# 管道和重定向
# 管道
ls | grep ".txt"
# 重定向
echo "log message" > output.log # 标准输出重定向
command 2> error.log # 错误输出重定向
command > output.log 2>&1 # 所有输出重定向
# 环境变量
# 查看所有环境变量
env
# 设置环境变量
export MY_VAR="value"
# 添加到PATH
export PATH="$PATH:/new/path"
# 常用快捷键
Ctrl + C
: 中断当前命令Ctrl + L
: 清屏Ctrl + R
: 搜索历史命令Ctrl + A
: 光标移到行首Ctrl + E
: 光标移到行尾
# 下一步
- 学习更多Shell命令
- 编写复杂的Shell脚本
- 了解系统管理任务
- 自动化日常工作