Skip to content

命令

文件与目录操作

ls —— 列出目录内容

shell
ls
ls -l # 详细信息(权限 / 所有者 / 大小 / 时间)
ls -la # 显示隐藏文件(. 开头)
ls -lh # 人类可读大小(KB/MB)
  • 示例
shell
ls -lah /etc/nginx

cd —— 切换目录

shell
cd /path
cd ..
cd ~
cd -
  • 技巧
    • cd -:回到上一个目录
    • ~:当前用户家目录

pwd —— 显示当前路径

shell
pwd

mkdir —— 创建目录

shell
mkdir test
mkdir -p a/b/c
  • -p:自动创建父目录

rm —— 删除文件/目录

shell
rm file.txt
rm -r dir
rm -rf dir
  • -r:递归
  • -f:强制(不会询问)

cp —— 复制

shell
cp a.txt b.txt
cp -r src dest

mv —— 移动 / 重命名

shell
mv old.txt new.txt
mv file /tmp/

touch —— 创建空文件 / 更新时间

shell
touch a.txt

文件查看与文本处理

cat —— 查看文件内容

shell
cat file.txt
  • 查看多个文件
shell
cat a.txt b.txt

less —— 分页查看

shell
less file.log
  • 快捷键
    • q:退出
    • /keyword:搜索
    • n:下一个匹配

head / tail

shell
head -n 20 file.txt
tail -n 50 file.log
tail -f file.log
  • -f:实时跟踪(日志神器)

grep —— 文本搜索

shell
grep "error" app.log
grep -i "error" app.log
grep -rn "main" .
  • 参数
    • -i:忽略大小写
    • -r:递归搜索
    • -n:显示行号

wc —— 统计行/词/字节

shell
wc file.txt
wc -l file.txt

sed —— 流式编辑

shell
sed 's/old/new/g' file.txt
sed -i 's/8080/80/g' nginx.conf

awk —— 列处理(日志分析)

shell
awk '{print $1,$3}' file.txt

权限与用户

chmod —— 修改权限

shell
chmod 755 script.sh
chmod +x script.sh
  • 权限说明
    • r=4 w=2 x=1
    • 755rwx r-x r-x

chown —— 修改所有者

shell
chown user:group file
chown -R www-data:www-data /var/www

whoami / id

shell
whoami
id

sudo —— 提权执行

shell
sudo apt update

进程与系统监控

ps —— 查看进程

shell
ps aux
ps -ef

top / htop

shell
top
htop

kill —— 杀进程

shell
kill 1234
kill -9 1234
  • -9:强制终止

free —— 内存

shell
free -h

df / du

shell
df -h
du -sh *

网络相关

ip / ifconfig

shell
ip a
ip route

ping

shell
ping baidu.com

curl —— HTTP 请求

shell
curl https://baidu.com
curl -X POST -d "a=1" http://localhost:3000

wget

shell
wget https://example.com/file.tar.gz

netstat / ss

shell
ss -lntp
netstat -tunlp

包管理

apt

shell
sudo apt update
sudo apt upgrade
sudo apt install nginx
sudo apt remove nginx

dpkg

shell
dpkg -l | grep nginx

压缩与解压

tar

shell
tar -czvf a.tar.gz dir
tar -xzvf a.tar.gz

zip / unzip

shell
zip -r a.zip dir
unzip a.zip

磁盘 & 挂载

lsblk

shell
lsblk

mount / umount

shell
mount /dev/sdb1 /mnt
umount /mnt

Shell 常用技巧

管道 |

shell
ps aux | grep nginx

重定向

shell
echo "hello" > a.txt
echo "world" >> a.txt

后台执行

shell
command &
nohup command &

开发 & 运维高频组合

shell
# 查端口占用
ss -lntp | grep 8080

# 查日志错误
tail -f app.log | grep error

# 查文件并删除
find . -name "*.log" -delete

# 批量替换
grep -rl "old" . | xargs sed -i 's/old/new/g'