Linux 文件与目录管理
增删改查、查找、打包压缩,以及软链接与硬链接的区别。
Key Points日常就是 ls/cd/cp/mv/rm/mkdir;找文件用 find,找内容用 grep,打包用 tar,链接优先用软链接。
基本操作
Bash
ls -lah # 详细 + 人类可读大小 + 隐藏文件
cd /var/log && cd -
mkdir -p /opt/app/{bin,conf,logs}
cp -a src/ dst/ # 保留属性递归复制
mv old.txt new.txt # 重命名;跨目录即移动
rm -rf /tmp/build # 慎用:删了不进回收站
touch app.log查看文件
Bash
cat /etc/hosts
less /var/log/syslog # 分页,/ 搜索,q 退出
head -20 access.log
tail -f -n 100 app.log # 跟踪日志
wc -l access.log查找
Bash
find /var/log -name "*.log" -mtime -1
find . -type f -size +100M
find . -name "*.tmp" -delete
grep -rn "DB_HOST" /opt/app/conf| Command | Searches | Speed |
|---|---|---|
find | File names, metadata | Slower, always accurate |
locate | Prebuilt index | Instant, may be stale |
grep -r | File contents | Depends on file count |
rg | Contents, respects .gitignore | Much faster |
打包压缩
Bash
tar -czf app.tar.gz app/ # 打包并 gzip
tar -xzf app.tar.gz -C /opt/ # 解包到指定目录
tar -tzf app.tar.gz | head # 先看内容再解
zip -r app.zip app/
unzip app.zip -d /opt/软链接与硬链接
Soft link (ln -s) | Hard link (ln) | |
|---|---|---|
| Points to | A path | The same inode |
| Survives target deletion | No, becomes dangling | Yes, data stays |
| Across filesystems | Yes | No |
| Directories | Yes | No |
Bash
ln -s /opt/app/releases/1.2.0 /opt/app/current
ls -l /opt/app/currentIf
$DIR is empty, rm -rf $DIR/ becomes rm -rf /. In scripts always write rm -rf "${DIR:?}/" so an empty variable aborts.基本操作
Bash
ls -lah # 详细 + 人类可读大小 + 隐藏文件
cd /var/log && cd -
mkdir -p /opt/app/{bin,conf,logs}
cp -a src/ dst/ # 保留属性递归复制
mv old.txt new.txt # 重命名;跨目录即移动
rm -rf /tmp/build # 慎用:删了不进回收站
touch app.log查看文件
Bash
cat /etc/hosts
less /var/log/syslog # 分页,/ 搜索,q 退出
head -20 access.log
tail -f -n 100 app.log # 跟踪日志
wc -l access.log查找
Bash
find /var/log -name "*.log" -mtime -1
find . -type f -size +100M
find . -name "*.tmp" -delete
grep -rn "DB_HOST" /opt/app/conf| 命令 | 查找对象 | 速度 |
|---|---|---|
find | 文件名、元数据 | 慢,但准确 |
locate | 预建索引 | 极快,可能过期 |
grep -r | 文件内容 | 取决于文件数 |
rg | 内容,遵守 .gitignore | 快得多 |
打包压缩
Bash
tar -czf app.tar.gz app/ # 打包并 gzip
tar -xzf app.tar.gz -C /opt/ # 解包到指定目录
tar -tzf app.tar.gz | head # 先看内容再解
zip -r app.zip app/
unzip app.zip -d /opt/软链接与硬链接
| 软链接 | 硬链接 | |
|---|---|---|
| 指向 | 路径 | 同一个 inode |
| 目标删除后 | 失效,成为断链 | 仍可访问 |
| 跨文件系统 | 可以 | 不行 |
| 目录 | 可以 | 不行 |
Bash
ln -s /opt/app/releases/1.2.0 /opt/app/current
ls -l /opt/app/currentrm -rf $DIR/ 里如果 $DIR 是空的,命令就变成 rm -rf /。脚本里务必写 rm -rf "${DIR:?}/",变量为空时直接报错退出。