入门基础
基本文件命令
ls -la 显示所有文件包括隐藏文件。cd ~ 回到主目录,cd - 在两个目录间切换。mkdir -p 按需创建父目录。rm -r 用于删除非空目录。
# list files
ls -la # long format, all files
ls -lh # human-readable sizes
ls -lt # sort by modification time
# current directory
pwd
# change directory
cd /home/user
cd .. # go up one level
cd ~ # go home
cd - # go to previous directory
# create/remove directories
mkdir newdir
mkdir -p path/to/dir # create parents
rmdir emptydir
rm -r nonempty # remove recursively获取帮助
man 是主要的文档系统。章节:1=命令,2=系统调用,3=库函数,4=设备,5=文件格式,8=管理。man -k(或 apropos)搜索描述。--help 给出简洁摘要。tldr 提供实用示例,需单独安装(npm install -g tldr)。
# manual pages
man ls # full documentation
man 5 crontab # section 5 (file formats)
man -k password # search by keyword (apropos)
# info pages (GNU tools, more detailed)
info coreutils
info ls
# quick help flags
command --help
ls --help
git --help
# tldr: community cheat sheets (install separately)
tldr tar
tldr find
# whatis: one-line description
whatis ls
# where is the binary / source / man page
whereis python3命令历史与快捷方式
!! 重复上一条命令(sudo !! 是经典的'忘记 sudo'修复法)。!N 运行历史中第 N 条命令。!$ 是最后一个参数。Ctrl+R 是交互式反向搜索——再按一次查找更早的匹配。历史记录存储在 ~/.bash_history;HISTSIZE 控制内存中的大小,HISTFILESIZE 控制文件大小。
# history expansion
history # show command history
!! # repeat last command
sudo !! # repeat last command as root
!42 # run command #42 from history
!ls # run last command starting with ls
!$ # last argument of last command
!!:gs/old/new/ # substitute in last command
# search history (interactive)
# Ctrl+R then type to search backward
# clear history
history -c # clear current session
# edit ~/.bashrc HISTSIZE and HISTFILESIZE
# save and reload history
history -a # append to history file
history -r # reload from file文件类型与识别
file 检查文件的魔数字节来确定其真实类型——比扩展名可靠得多。ls -F 附加类型标识(* 可执行,/ 目录,@ 符号链接,= 套接字)。stat 显示完整的 inode 元数据,包括三个时间戳:Access(atime)、Modify(mtime,内容)、Change(ctime,元数据)。
# identify file type by content (not extension)
file document.pdf # PDF document
file image.png # PNG image data
file script.sh # ASCII text executable
file /bin/ls # ELF 64-bit LSB executable
# file with multiple files
file *.txt
# show MIME type
file --mime-type video.mp4 # video/mp4
# ls -F shows type indicator
ls -F
# file* (executable)
# dir/ (directory)
# link@ (symlink)
# socket= (socket)
# stat: detailed file info
stat file.txt
# Size, Blocks, IO Block, Device, Inode, Links,
# Access/Modify/Change/Birth times终端导航快捷键
这些 Readline 快捷键在 bash 和大多数 shell 中通用。Ctrl+A/E 跳到行首/行尾。Ctrl+W/U/K 删除文本——Ctrl+Y 粘贴回来(kill ring)。Ctrl+R 搜索历史。Ctrl+L 清屏。Ctrl+S 冻结输出(常见的'终端假死'原因——Ctrl+Q 恢复)。掌握这些可以大幅提升命令行编辑速度。
# cursor movement
Ctrl+A # move to beginning of line
Ctrl+E # move to end of line
Ctrl+B # move back one char
Ctrl+F # move forward one char
# editing
Ctrl+D # delete char under cursor (or EOF/exit)
Ctrl+H # delete char before cursor (backspace)
Ctrl+W # delete word before cursor
Ctrl+U # delete from cursor to beginning
Ctrl+K # delete from cursor to end
Ctrl+Y # paste (yank) deleted text back
# job control
Ctrl+C # send SIGINT (interrupt)
Ctrl+Z # suspend (send SIGTSTP)
Ctrl+D # end of input / exit shell
# screen
Ctrl+L # clear screen (same as clear)
Ctrl+S # stop output (freeze)
Ctrl+Q # resume output
# Alt shortcuts
Alt+B / Alt+F # move back/forward by word
Alt+Backspace # delete word backward环境变量
环境变量在导出后被子进程继承。$PATH 决定 shell 查找命令的位置——目录按冒号分隔的顺序搜索。~/.bashrc 用于交互式非登录 shell;~/.profile 或 ~/.bash_profile 用于登录 shell。编辑后始终 source 文件以应用更改。使用 printenv VAR 检查单个变量而不进行扩展。
# view all environment variables
env
printenv
# view specific variable
echo $HOME
echo $PATH
echo $USER
# set a variable (current shell only)
MYVAR="hello"
echo $MYVAR
# export to child processes
export PATH="$PATH:/opt/bin"
export EDITOR=nano
# set and export in one step
export MYVAR="hello"
# unset a variable
unset MYVAR
# common variables
# $HOME user home directory
# $PATH command search path
# $USER current username
# $SHELL current shell path
# $PWD current working directory
# $OLDPWD previous directory
# $PS1 prompt string
# persistent: add to ~/.bashrc or ~/.profile
echo 'export EDITOR=vim' >> ~/.bashrc
source ~/.bashrc文件操作
复制文件 (cp)
cp 复制文件。目录需要 -r(或 -R)。-i 在覆盖前提示(建议以避免数据丢失)。-p 保留元数据;-a 是归档模式(保留所有内容,包括符号链接——非常适合备份)。-u 仅在源文件更新时才复制。在覆盖有风险的脚本中始终使用 -i。
# copy a file
cp source.txt dest.txt
# copy to a directory
cp file.txt /backup/
# copy multiple files to a directory
cp file1.txt file2.txt /backup/
# copy directories recursively
cp -r src_dir/ dest_dir/
# interactive (prompt before overwrite)
cp -i file.txt /backup/
# preserve attributes (timestamps, permissions, ownership)
cp -p file.txt /backup/
cp -a src_dir/ dest_dir/ # archive mode (-rdp)
# only copy if source is newer
cp -u file.txt /backup/
# verbose (show what is being copied)
cp -v file.txt /backup/
# force overwrite
cp -f file.txt /backup/移动与重命名 (mv)
mv 既是移动也是重命名——它更新目录条目而不复制数据(在同一文件系统上瞬时完成)。-i 在覆盖前提示。mv -n 防止覆盖已有文件。rename 命令(Debian/Ubuntu 上的 Perl 版本)使用正则表达式批量重命名——比 mv 循环强大得多。注意:rename 语法因发行版而异(util-linux vs perl 版本)。
# rename a file
mv oldname.txt newname.txt
# move file to another directory
mv file.txt /target/dir/
# move multiple files
mv file1.txt file2.txt /target/dir/
# interactive (prompt before overwrite)
mv -i file.txt /target/
# force overwrite
mv -f file.txt /target/
# no overwrite (don't replace existing)
mv -n file.txt /target/
# move only if newer
mv -u file.txt /target/
# verbose
mv -v olddir/ newdir/
# rename batch with rename command
rename 's/\.txt$/.md/' *.txt
rename .JPG .jpg *.JPG删除文件 (rm)
rm 永久删除文件(没有回收站)。目 录需要 -r。-rf 很危险——它递归删除且不提示;始终仔细检查路径。永远不要运行 rm -rf / 或在 $VAR 可能为空时运行 rm -rf $VAR/。考虑使用 trash-cli 进行可恢复的删除。find -delete 用于基于模式的删除更安全,因为可以先不带 -delete 测试。
# remove a file
rm file.txt
# remove multiple files
rm file1.txt file2.txt
# interactive (prompt for each file)
rm -i file.txt
# force (ignore nonexistent, no prompt)
rm -f file.txt
# remove directory recursively
rm -r directory/
rm -rf directory/ # force + recursive (DANGEROUS)
# verbose
rm -v *.tmp
# remove files matching pattern
find . -name "*.bak" -delete
find . -name "*.log" -mtime +30 -delete
# safer alternative: trash-cli
trash-put file.txt
trash-list
trash-restore创建文件 (touch)
touch 创建空文件或更新现有文件的时间戳。不带选项时,它将 atime 和 mtime 都设为当前时间。-t 设置特定时间戳。-r 从参考文件复制时间戳。要创建带内容的文件,使用重定向(>)或 here-document。touch 常用于创建占位文件或强制 make 重新构建目标。
# create an empty file
touch newfile.txt
# create multiple empty files
touch file1.txt file2.txt file3.txt
# update access and modification time to now
touch existing.txt
# set specific time (YYYYMMDDHHMM format)
touch -t 202401011200 file.txt # Jan 1, 2024 12:00
# set only access time
touch -a file.txt
# set only modification time
touch -m file.txt
# use time from another file
touch -r reference.txt target.txt
# create file with content
echo "content" > file.txt
cat > file.txt << 'EOF'
line 1
line 2
EOF硬链接与符号链接 (ln)
硬链接共享相同的 inode(数据)——删除一个不会删除数据,直到所有链接都被移除。它们不能跨文件系统或链接到目录。符号链接是路径引用——如果目标移动或删除则会断开,但可以跨文件系统和链接到目录。使用 ln -s 创建符号链接(最常用)。readlink -f 解析完整链到真实文件。
# hard link (same inode, same filesystem only)
ln original.txt hardlink.txt
# symbolic link (symlink, path reference)
ln -s /path/to/target symlink_name
ln -s original.txt softlink.txt
# force recreate a symlink
ln -sf /new/target symlink_name
# symbolic link to a directory
ln -s /var/log /home/user/logs
# view link target
readlink symlink
readlink -f symlink # canonical absolute path
ls -l symlink # show what it points to
# find broken symlinks
find . -type l ! -exec test -e {} \; -print
# count hard links to a file
ls -li file.txt # 2nd column is link count
# remove a symlink
rm symlink_name
unlink symlink_name文件元数据 (stat, basename, dirname)
stat 显示完整的 inode 元数据。basename 和 dirname 分解路径——在处理文件列表的脚本中必不可少。realpath 将相对路径和符号链接解析为绝对规范路径。stat -c 允许自定义输出格式(%n=名称,%s=大小,%y=mtime,%a=八进制权限)——在脚本中很有用。这些工具替代了脆弱的参数扩展来处理路径。
# stat: full file information
stat file.txt
# Size: 1024 Blocks: 8 IO Block: 4096
# Device: 801h/2049d Inode: 1234567
# Links: 1
# Access: (0644/-rw-r--r--) Uid: 1000 Gid: 1000
# Access/Modify/Change: 2024-01-01 12:00:00
# custom format
stat -c '%n %s bytes' file.txt
stat -c '%y' file.txt # modification time
# basename: extract filename from path
basename /var/log/syslog # syslog
basename /var/log/syslog.log .log # syslog
# dirname: extract directory from path
dirname /var/log/syslog # /var/log
# realpath: resolve to absolute path
realpath ../file.txt
realpath -s symlink # physical path (no symlink resolution)
# file size only
stat -c %s file.txt # bytes
du -h file.txt | cut -f1 # human-readable目录操作
创建目录 (mkdir)
mkdir -p 按需创建父目录,且目录已存在时不报错——对幂等脚本至关重要。-m 直接设置权限(覆盖 umask)。大括号扩展({a,b,c})与 mkdir -p 结合可一条命令创建复杂的目录树。这是搭建项目结构的常见模式。
# create a single directory
mkdir newdir
# create nested directories
mkdir -p path/to/deep/dir
# create multiple directories
mkdir dir1 dir2 dir3
# create with specific permissions
mkdir -m 755 publicdir
mkdir -m 700 privatedir
# verbose output
mkdir -v newdir
# create parent dirs with permissions
mkdir -p -m 755 /opt/myapp/{bin,lib,etc}
# create a directory tree at once
mkdir -p project/{src,tests,docs}
mkdir -p project/src/{main,utils}
mkdir -p project/{src/{main,utils},tests,docs}删除目录 (rmdir, rm)
rmdir 只删除空目录——安全但有限。rm -r 递归删除非空目录。rm -rf 是核武器选项:始终先验证路径。find -empty -delete 模式只删除空目录而不触及有内容的目录。在脚本中,始终检查变量非空后再用 rm -rf,以避免意外删除 /。
# remove an empty directory
rmdir emptydir
# remove directory with contents
rm -r directory/
# force remove (no prompt)
rm -rf directory/
# remove empty directories recursively (find)
find . -type d -empty -delete
find . -type d -empty -exec rmdir {} \;
# remove directory with confirmation
rm -ri directory/
# safe removal pattern in scripts
DIR="/tmp/mydir"
if [ -n "$DIR" ] && [ -d "$DIR" ]; then
rm -rf "$DIR"
fi
# move to trash instead
trash-put directory/目录列表与树形结构
ls -d */ 只列出目录。tree 提供可视化的层级结构——-L 限制深度,-I 排除模式(排除 node_modules/.git 非常有用)。对于大型目录树,结合 tree -d -L 2 快速概览。ls -1(数字 1)每行一个文件——用于管道到 wc -l 计数很方便。
# list directory contents
ls -la # all files, long format
ls -lh # human-readable sizes
ls -lt # sort by time (newest first)
ls -lS # sort by size (largest first)
ls -lr # reverse order
ls -R # recursive listing
ls -d */ # list only directories
# tree view (install separately: apt install tree)
tree # show directory tree
tree -L 2 # limit depth to 2
tree -d # directories only
tree -a # include hidden files
tree -h # show file sizes
tree --dirsfirst # dirs before files
tree -I 'node_modules|.git' # ignore patterns
tree -H . -o tree.html # output as HTML
# count files in directory
ls -1 | wc -l
find . -maxdepth 1 -type f | wc -l目录大小 (du)
du 测量磁盘使用量。-s(摘要)只显示总计,-h 使其人类可读。du -sh */ 显示直接子目录的大小。sort -rh 按人类可读大小倒序排列(最大的在前)。--exclude 跳过模式。apparent-size 与默认值的区别:apparent 显示逻辑文件大小,默认显示实际分配的磁盘块(由于块大小可能更大)。
# size of current directory (total)
du -sh .
# size of specific directories
du -sh /var/log /tmp /home
# size of all subdirectories
du -sh */
# sort directories by size (largest first)
du -sh * | sort -rh
# find the 10 largest directories
du -sh * | sort -rh | head -10
# include hidden files/dirs
du -sh .[!.]*
# maximum depth
du -h --max-depth=1
du -h -d 1 # short form
# apparent size vs disk usage
du -sh --apparent-size file # logical size
du -sh file # actual disk blocks
# exclude directories
du -sh --exclude='*.log' .
du -sh --exclude=node_modules .目录栈 (pushd, popd)
pushd/popd 管理目录栈——pushd 保存当前目录并导航到新目录;popd 返回到保存的目录。dirs 显示栈。这比 cd -(只在两个目录间切换)更强大。在需要在多个目录间导航并返回的脚本中很有用。+N 语法按位置轮转或移除。
# push directory onto stack and cd into it
pushd /var/log
# pushes current dir, then cd to /var/log
# push another
pushd /tmp
# stack: /tmp /var/log /home/user
# pop back to previous directory
popd
# returns to /var/log
# list the directory stack
dirs
dirs -v # verbose (numbered)
dirs -c # clear the stack
# navigate by index
pushd +2 # rotate to 3rd entry
popd +1 # remove 2nd entry
# practical: save current dir, work, return
pushd /etc
cp config.conf ~/backup/
popd # back to where we were
# alternative: use cd - for simple toggle
cd /var/log
cd - # back to previous directory文件查看
cat 与 tac
cat 将整个文件输出到 stdout——小文件没问题,大文件请用 less/head。cat -n 编号行。cat -A 显示隐藏字符(制表符、行尾)——调试格式问题很有用。tac 反转行序(cat 的倒序)。cat 也用于连接文件和重定向输入。交互式查看大文件请使用 less。
# display entire file
cat file.txt
# concatenate multiple files
cat file1.txt file2.txt > combined.txt
# display with line numbers
cat -n file.txt
# display with non-printing characters
cat -A file.txt # show tabs as ^I, line ends as $
cat -v file.txt # show non-printing chars
cat -e file.txt # show line ends as $
cat -t file.txt # show tabs as ^I
# append to a file
cat >> file.txt << 'EOF'
appended line
EOF
# tac: reverse line order
tac file.txt # last line first
# create file from stdin
cat > newfile.txt
# type content, Ctrl+D to endless 分页器
less 是标准分页器——比 more 好得多,因为它允许向后导航。按键类似 vim(j/k/g/G)。/ 向前搜索,? 向后搜索。F 进入'跟随模式'(类似 tail -f)用于查看日志。如果配置了 lesspipe,less 会自动处理压缩文件。按 v 在 $EDITOR 中打开当前文件进行快速编辑。
# view a file
less file.txt
# view command output
dmesg | less
ls -la /etc | less
# navigation inside less:
# space / f forward one page
# b backward one page
# j / k down / up one line
# g go to beginning
# G go to end
# /pattern search forward
# ?pattern search backward
# n next match
# N previous match
# v open in editor ($EDITOR)
# F follow mode (like tail -f)
# q quit
# useful flags
less -N file.txt # show line numbers
less -S file.txt # chop long lines
less -i file.txt # case-insensitive search
less +/pattern file.txt # open at first match
# view compressed files
less file.gz # auto-decompresses (if lesspipe installed)head 与 tail
head 显示文件开头,tail 显示文件末尾。tail -f 对于实时监控日志文件至关重要。tail -F(大写)通过重新打开文件处理文件轮转(当日志被重命名/截断时)。head -n -N 显示除最后 N 行外的所有内容。对于大文件,head/tail 是即时的(它们不会读取整个文件)。
# first 10 lines (default)
head file.txt
# last 10 lines (default)
tail file.txt
# first N lines
head -n 20 file.txt
head -20 file.txt
# last N lines
tail -n 20 file.txt
tail -20 file.txt
# all but last N lines
head -n -5 file.txt # all except last 5 lines
# first N bytes
head -c 100 file.txt
tail -c 100 file.txt
# follow a log file (live updates)
tail -f /var/log/syslog
# follow with retry (handles log rotation)
tail -F /var/log/app.log
# show last 5 lines, then follow
tail -n 5 -f app.log
# multiple files
tail -n 5 file1.txt file2.txt查看特定行
sed -n 'Np' 打印特定行号。awk 配合 NR(记录号)对范围和条件更灵活。(head; tail) 技巧显示大文件的两端。nl 和 cat -n 编号行。hexdump/xxd 以十六进制显示二进制文件——检查非文本文件、调试文件格式或恢复数据的必备工具。
# show line N (e.g., line 10)
sed -n '10p' file.txt
# show lines M to N
sed -n '10,20p' file.txt
awk 'NR>=10 && NR<=20' file.txt
# show first and last N lines
(head -5; echo "..."; tail -5) < file.txt
# show lines matching pattern
sed -n '/pattern/p' file.txt
awk '/pattern/' file.txt
# show every Nth line
awk 'NR % 3 == 0' file.txt # every 3rd line
sed -n '0~3p' file.txt # every 3rd line (GNU)
# number lines
nl file.txt
cat -n file.txt
grep -n "" file.txt
# show file in hex
hexdump -C file.bin
xxd file.bin
od -A x -t x1z file.bin字数与行数统计 (wc)
wc(word count)报告行数(-l)、单词数(-w)、字节数(-c)、字符数(-m,尊重编码)和最长行长度(-L)。给定多个文件时,显示每个文件的计数和总计。grep | wc -l 模式计算匹配行——但 grep -c 更高效(无管道)。计算文件数时,ls -1 | wc -l 很快,但 find 递归计数更准确。
# count lines, words, and bytes
wc file.txt
# 10 50 300 file.txt
# lines words bytes
# count lines only
wc -l file.txt
# count words only
wc -w file.txt
# count characters only
wc -m file.txt
# count bytes only
wc -c file.txt
# count the longest line length
wc -L file.txt
# count files in a directory
ls -1 | wc -l
find . -type f | wc -l
# count total lines in multiple files
wc -l *.py
# count matching lines (grep + wc)
grep "error" log.txt | wc -l
# count unique lines
sort file.txt | uniq | wc -l文件搜索
find 按名称与类型
find 是最强大的文件搜索工具。-name 用 glob 模式匹配文件名;-iname 不区分大小写。-type 按文件类型过滤(f=文件,d=目录,l=符号链接)。-maxdepth 限制递归(对性能很重要)。-not 和 -prune 排除路径。\( -name A -o -name B \) 用 OR 分组条件。始终引用模式以防止 shell glob 扩展。