Quick check of common Linux commands
This article organizes common commands according to daily Linux usage scenarios. in the example <file>、<directory>、<user>、<pid> Content such as content needs to be replaced with the actual file name, directory, user name or process number.
Some commands require administrator privileges and can be added before the command sudo。Before performing operations such as deleting files, modifying permissions, terminating processes, or partitioning disks, you should first confirm whether the operation object is correct.
Common Linux catalogs
| directory | description |
|---|---|
/ | root directory |
/home | General user home directory |
/root | root user home directory |
/etc | System and software profiles |
/var | Frequently changing data such as logs, caches |
/var/log | System and service logs |
/usr | User programs and shared resources |
/usr/bin | frequently used commands |
/usr/local | Locally installed software |
/opt | third-party software |
/tmp | temporary files |
/dev | device file |
/proc | Process and kernel operation information |
/sys | Core and hardware device information |
/mnt | temporary mount directory |
/media | Mounting catalog for removable devices such as USB flash drives and optical discs |
View the current environment
View current user name
whoamiView the current directory
pwdView currently logged in users
whoView more detailed login information
wView host name
hostnameView system runtime and load
uptimeView Linux kernel version
uname -rView complete system information
uname -aView release information
cat /etc/os-releaseCheck system time
datebrowse the directory
View the current directory content
lsView in detailed format
ls -lShow Hidden Files
ls -aDisplay hidden files and display file size in an easy-to-read manner
ls -lahSort by modification time
ls -ltSort by file size
ls -lhSswitch directory
Enter the specified directory
cd <directory>Return to the previous directory
cd ..Return to user home directory
cd ~You can also use directly:
cdReturn to the previous directory
cd -Enter the root directory
cd /create files and directories
create an empty file
touch <file>Creating multiple files simultaneously
touch file1.txt file2.txt file3.txtcreate a directory
mkdir <directory>Recursively create a multi-level directory
mkdir -p path/to/directoryCreate multiple directories simultaneously
mkdir dir1 dir2 dir3Copying files and directories
copy files
cp <source> <destination>Copy the file and rename it
cp source.txt backup.txtRecursively copy directory
cp -r <source-directory> <destination-directory>Retain permissions, timestamps and other attributes copying
cp -a <source> <destination>Prompt before overwriting files
cp -i <source> <destination>Move and rename files
move files
mv <source> <destination>rename files
mv old-name.txt new-name.txtmobile directory
mv <directory> <destination>Prompt before overwriting target file
mv -i <source> <destination>delete files and directories
delete files
rm <file>delete multiple files
rm file1.txt file2.txtDelete empty directory
rmdir <directory>Recursively delete directories and their contents
rm -r <directory>Confirm before deleting
rm -ri <directory>+++Danger:rm -rf
rm -rf Target directories will be recursively and forcibly deleted, will not enter the Recycle Bin, and will not be interrogated one by one.
For example:
rm -rf <directory>Be especially cautious when using variables or wildcards. You can pass it before implementation ls Check the match results:
ls <target>Confirm that there is no error before performing the deletion operation. +++
view the file contents
Export entire file
cat <file>displays line numbers
cat -n <file>Pagination to view long files
less <file>in less Middle:
↑ / ↓ 上下移动
Space 下一页
b 上一页
/keyword 搜索
n 下一个匹配
q 退出View the first 10 lines of the file
head <file>View the first 20 lines of the file
head -n 20 <file>View the last 10 lines of the file
tail <file>View the last 50 lines of the file
tail -n 50 <file>View new content in files in real time
tail -f <file>Commonly used to view logs:
tail -f /var/log/syslogedit the file
Editing files with Nano
nano <file>Common shortcut keys:
Ctrl + O 保存
Ctrl + X 退出
Ctrl + W 搜索Editing files with Vim
vim <file>Common operations:
i 进入插入模式
Esc 返回普通模式
:w 保存
:q 退出
:wq 保存并退出
:q! 放弃修改并退出
/word 搜索
dd 删除当前行
yy 复制当前行
p 粘贴
u 撤销file search
Find by file name
find <directory> -name "<filename>"For example:
find /etc -name "nginx.conf"Ignore case lookups
find <directory> -iname "<filename>"Find the specified extension file
find . -name "*.log"Find a catalog
find . -type d -name "<directory-name>"find files
find . -type f -name "<filename>"Find files that have been modified in the last day
find . -type f -mtime -1Find files larger than 100 MB
find . -type f -size +100MFind command location
which <command>For example:
which python3Find command, source code and manual locations
whereis <command>search text
Search for strings in files
grep "<keyword>" <file>ignore case
grep -i "<keyword>" <file>Display matching line numbers
grep -n "<keyword>" <file>Recursive search directory
grep -r "<keyword>" <directory>Recursively searches and displays line numbers
grep -rn "<keyword>" <directory>Eliminate matches
grep -v "<keyword>" <file>Use extended regular expressions
grep -E "<pattern>" <file>Searching for running processes
ps aux | grep <process-name>use grep When searching for the process, the results usually appear grep Command itself. may be used pgrep Streamline process lookup.
File compression and decompression
Create a tar archive
tar -cvf archive.tar <directory>Extract tar archives
tar -xvf archive.tarCreate a gzip archive
tar -czvf archive.tar.gz <directory>Unpack tar.gz
tar -xzvf archive.tar.gzCreate an xz archive
tar -cJvf archive.tar.xz <directory>Unpack tar.xz
tar -xJvf archive.tar.xzView the contents of the compressed package but do not decompress it
tar -tvf archive.tar.gzExtract it to the specified directory
tar -xzvf archive.tar.gz -C <directory>Create a ZIP archive
zip -r archive.zip <directory>extracting ZIP
unzip archive.zipExtract ZIP to the specified directory
unzip archive.zip -d <directory>file permissions
Linux file permissions are divided into:
r = read 读取
w = write 写入
x = execute 执行Permission objects are divided into:
u = user 文件所有者
g = group 所属用户组
o = others 其他用户
a = all 所有用户View file permissions
ls -l <file>For example:
-rwxr-xr-- 1 qzh qzh 1024 Sep 2 12:00 script.shAmong them:
rwx 所有者权限
r-x 用户组权限
r-- 其他用户权限Increase execution rights for owners
chmod u+x <file>Remove write permissions from other users
chmod o-w <file>Add execution rights for all users
chmod a+x <file>Use numbers to set permissions
chmod 755 <file>Digital authority correspondence:
| digital | permissions |
|---|---|
0 | --- |
1 | --x |
2 | -w- |
3 | -wx |
4 | r-- |
5 | r-x |
6 | rw- |
7 | rwx |
Common permissions:
chmod 644 <file>
chmod 755 <file>
chmod 600 <file>Among them:
644 普通文本文件常见权限
755 可执行程序或目录常见权限
600 私钥等敏感文件常见权限recursively modify directory permissions
chmod -R 755 <directory>Modify file owner
Modify file owner
sudo chown <user> <file>Modify both owners and user groups
sudo chown <user>:<group> <file>Recursively modify the directory owner
sudo chown -R <user>:<group> <directory>Modify the user group to which the file belongs
sudo chgrp <group> <file>user management
View current user UIDs and user groups
idView specified user information
id <user>create user
sudo adduser <user>delete user
sudo deluser <user>Delete users and their home directories
sudo deluser --remove-home <user>Modify the current user password
passwdModify the specified user password
sudo passwd <user>switch user
su - <user>su to root user
sudo -iExecute a single command with root privileges
sudo <command>user group Management
View the user group to which the current user belongs
groupsView the user group to which the specified user belongs
groups <user>create user groups
sudo groupadd <group>Add users to user groups
sudo usermod -aG <group> <user>For example, adding users docker User Group:
sudo usermod -aG docker <user>use usermod -aG After modifying a user group, you usually need to log in again to fully take effect.
Remove users from user groups
sudo gpasswd -d <user> <group>process management
View the current terminal process
psView all processes in the system
ps auxView processes in tree structure
ps auxfDynamic view of system processes
topif you installed a htop:
htopFind PID based on process name
pgrep <process-name>Display both process name and PID
pgrep -a <process-name>Terminate the specified process
kill <pid>Force termination of specified process
kill -9 <pid>Terminate a process based on name
pkill <process-name>Force process termination based on name
pkill -9 <process-name>kill -9 will be sent directly SIGKILLThe process has no opportunity to perform cleanup work. Usually try ordinary first kill <pid>, consider using it only if the process cannot exit normally kill -9。
Running tasks in the background
Put the command in the background and run it
<command> &View the current Shell background tasks
jobsSwitch background tasks to the foreground
fg %1Continue suspended tasks to run in the background
bg %1Let the program exit the terminal and continue running
nohup <command> &For example:
nohup python3 app.py > app.log 2>&1 &View the daemon PID
echo $!systemd service management
Modern Ubuntu, Debian, Rocky Linux, CentOS and other distributions are commonly used systemd Manage system services.
Check service status
systemctl status <service>For example:
systemctl status sshstart the service
sudo systemctl start <service>stop service
sudo systemctl stop <service>restart the service
sudo systemctl restart <service>Reload service configuration
sudo systemctl reload <service>Set up service startup
sudo systemctl enable <service>Start immediately and set up booting
sudo systemctl enable --now <service>Cancel booting
sudo systemctl disable <service>Check whether the service is turned on
systemctl is-enabled <service>Check if the service is running
systemctl is-active <service>View failed services
systemctl --failedView systemd logs
view system logs
journalctlView the specified service log
journalctl -u <service>View service logs in real time
journalctl -u <service> -fView the last 100 rows of logs
journalctl -u <service> -n 100Check the logs since this launch
journalctl -bView the log of the last boot
journalctl -b -1View the latest hour's log
journalctl --since "1 hour ago"View CPU and memory
View CPU information
lscpuCheck the number of CPU cores
nprocCheck memory usage
free -hObserve memory changes in real time
watch -n 1 free -hView system load
uptimeYou can also use:
cat /proc/loadavgView disk space
View file system disk usage
df -hDisplay file system type also
df -ThView the file system space where the specified directory is located
df -h <directory>View the current directory size
du -sh .View the specified directory size
du -sh <directory>View the size of each file and directory in the current directory
du -sh *sorted by size
du -sh * | sort -hView the top 20 projects in the current catalog
du -ah . | sort -rh | head -n 20View disks and partitions
View Block Devices
lsblkDisplay file system type and UUID
lsblk -fView disk partition information
sudo fdisk -lView File System UUID
sudo blkidCheck the current mounting status
findmntMount the file system
Create a mount directory
sudo mkdir -p /mnt/dataMount partition
sudo mount <device> /mnt/dataFor example:
sudo mount /dev/sdb1 /mnt/dataunmount the file system
sudo umount /mnt/dataYou can also uninstall through your device:
sudo umount /dev/sdb1View permanent mount configuration
cat /etc/fstabmodify /etc/fstab It is recommended to back up first:
sudo cp /etc/fstab /etc/fstab.bakAfter the modifications are complete, you can test the configuration using the following commands:
sudo mount -aIf the command does not report an error, consider restarting the system.
Common LVM commands
View physical volumes
sudo pvsView Volume Group
sudo vgsView logical volumes
sudo lvsView detailed logical volume information
sudo lvdisplayAllocate all free space in a volume group to logical volumes
sudo lvextend -l +100%FREE <logical-volume>For example:
sudo lvextend -l +100%FREE /dev/ubuntu-vg/ubuntu-lvExpand the ext4 file system
sudo resize2fs <logical-volume>Capacity expansion of XFS file system
sudo xfs_growfs <mount-point>The risks of shrinking logical volumes and file systems are significantly higher than those of expanding them. Before performing LVM modifications, you should first confirm the device path, file system type, and backup status.
network information
View network card and IP address
ip addrAbbreviations:
ip aView only IPv4 addresses
ip -4 addrview the routing table
ip routeAbbreviations:
ip rView default gateway
ip route | grep defaultView neighbor and ARP information
ip neighView DNS configuration
cat /etc/resolv.confusing systemd-resolved Can also be used in the system:
resolvectl statusNetwork connectivity testing
Test whether the target host is reachable
ping <host>Stop after sending 4 packets
ping -c 4 <host>View the routes taken to reach the target host
traceroute <host>if it is not installed traceroute, some systems can use:
tracepath <host>Query domain name resolution
nslookup <domain>You can also use:
dig <domain>Query the specified record
dig <domain> A
dig <domain> AAAA
dig <domain> MXview the port
Check the TCP and UDP ports you are listening on
ss -tulnDisplay the corresponding process at the same time
sudo ss -tulpnView the specified port
sudo ss -tulpn | grep :<port>For example, check the 8080 port:
sudo ss -tulpn | grep :8080View the processes occupying the specified port
sudo lsof -i :<port>For example:
sudo lsof -i :8080HTTP request
Get web content
curl <url>View only response headers
curl -I <url>Follow HTTP redirection
curl -L <url>Download the file and keep the original file name
curl -O <url>Download the file and specify the file name
curl -o <filename> <url>Send GET request and display details
curl -v <url>Send POST request
curl -X POST <url>Send JSON data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"test"}' \
<url>Download files using wget
download files
wget <url>Specify the save file name
wget -O <filename> <url>breakpoint continuous transmission
wget -c <url>background download
wget -b <url>SSH remote login
Log in to the remote server
ssh <user>@<host>Specify the SSH port
ssh -p <port> <user>@<host>specify a private key
ssh -i <private-key> <user>@<host>remote command execution
ssh <user>@<host> "<command>"For example:
ssh qzh@192.168.1.10 "hostname"SSH key
Create Ed25519 key
ssh-keygen -t ed25519 -C "you@example.com"Create an RSA key
ssh-keygen -t rsa -b 4096 -C "you@example.com"Copy the public key to the remote server
ssh-copy-id <user>@<host>View public key
cat ~/.ssh/id_ed25519.pubTest SSH configuration
ssh -v <user>@<host>SCP file transfer
Upload local files to remote server
scp <file> <user>@<host>:<remote-path>Download files from remote servers
scp <user>@<host>:<remote-file> <local-path>Recursively upload directory
scp -r <directory> <user>@<host>:<remote-path>Specify the SSH port
scp -P <port> <file> <user>@<host>:<remote-path>ssh use lowercase -p Specify the port, and scp using uppercase -P。
rsync file synchronization
synchronize directory
rsync -av <source>/ <destination>/Display synchronization progress
rsync -av --progress <source>/ <destination>/Sync to remote server via SSH
rsync -av <source>/ <user>@<host>:<destination>/Sync from remote server to local
rsync -av <user>@<host>:<source>/ <destination>/Delete unnecessary files on the target side to make both ends completely consistent
rsync -av --delete <source>/ <destination>/--delete Files in the destination directory that do not exist in the source directory will be deleted. Can be added before formal implementation --dry-run Preview operation:
rsync -av --delete --dry-run <source>/ <destination>/APT package management
Suitable for Ubuntu, Debian and other distributions.
Update software package index
sudo apt updateUpgrade installed software packages
sudo apt upgradeinstall software
sudo apt install <package>Remove software but retain configuration
sudo apt remove <package>Remove software and its configuration
sudo apt purge <package>Clean up dependencies that you no longer need
sudo apt autoremoveSearch software packages
apt search <keyword>View package information
apt show <package>View installed packages
apt list --installedDNF package management
Suitable for Fedora, Rocky Linux, AlmaLinux and other distributions.
update package
sudo dnf upgradeinstall software
sudo dnf install <package>remove software
sudo dnf remove <package>Search software packages
dnf search <keyword>View package information
dnf info <package>environment variable
View all environment variables
envView specified environment variables
echo $PATHTemporarily set environment variables
export NAME=valueFor example:
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64Add directories to your PATH
export PATH="$PATH:/opt/example/bin"View the current Shell
echo $SHELLReload Bash configuration
source ~/.bashrcIt can also be written as:
. ~/.bashrcShell redirection
Write standard output to a file and overwrite the original content
<command> > output.txtAppend standard output to a file
<command> >> output.txtWrite standard errors to file
<command> 2> error.logSave both standard output and standard errors
<command> > output.log 2>&1You can also use it in Bash:
<command> &> output.logdiscard standard output
<command> > /dev/nullDiscard standard output and error output
<command> > /dev/null 2>&1pipeline
pipeline | The standard output of the previous command is used as the standard input of the subsequent command.
search command output
<command> | grep "<keyword>"paging view command output
<command> | lessStatistics output rows
<command> | wc -lDelete duplication after sorting
<command> | sort | uniqSort by number
<command> | sort -nreverse order arrangement
<command> | sort -rtext processing
Count the number of file rows
wc -l <file>Count the number of words
wc -w <file>Count the number of bytes
wc -c <file>Sort file content
sort <file>Remove adjacent duplicate rows
uniq <file>usually cooperate sort Use:
sort <file> | uniqCount the number of duplicate rows
sort <file> | uniq -cExtract specified column
cut -d '<delimiter>' -f <field> <file>such as read /etc/passwd User name in:
cut -d ':' -f 1 /etc/passwdAwk common operations
Output first column
awk '{print $1}' <file>Output the first and third columns
awk '{print $1, $3}' <file>specified delimiter
awk -F ':' '{print $1}' /etc/passwdFilter by condition
awk '$3 > 100 {print $1, $3}' <file>SED Common operations
Replace the first match
sed 's/old/new/' <file>Replace all matches in one line
sed 's/old/new/g' <file>Modify files directly
sed -i 's/old/new/g' <file>Delete blank lines
sed '/^$/d' <file>sed -i The original document will be directly modified. It is recommended to back up important files first or remove them first -i Check the replacement results.
command history
View historical commands
historyView the last 20 orders
history 20Search history command
history | grep "<keyword>"Implement the previous order
!!Execute the historical command of the specified number
!<number>Clear the current Shell history
history -cReverse search history command
In the terminal, press:
Ctrl + REnter keywords to search for previously executed commands.
command assistance
View the command manual
man <command>For example:
man lsView Command Help
<command> --helpFor example:
ls --helpView Shell built-in command help
help <command>For example:
help cdView command types
type <command>alias command alias
View current aliases
aliasTemporarily create alias
alias ll='ls -lah'delete an alias
unalias llPermanently add aliases
Write the alias to:
~/.bashrcFor example:
alias ll='ls -lah'
alias gs='git status'Then reload:
source ~/.bashrcTiming task Cron
Edit scheduled tasks for current users
crontab -eView current user's scheduled tasks
crontab -lDelete all Cron tasks for current users
crontab -rBasic Cron format:
分 时 日 月 周 命令
* * * * *
│ │ │ │ │
│ │ │ │ └── 星期:0-7,0 和 7 都表示星期日
│ │ │ └───── 月份:1-12
│ │ └──────── 日期:1-31
│ └─────────── 小时:0-23
└────────────── 分钟:0-59Execution of scripts at 2 a.m. every day
0 2 * * * /path/to/script.shExecuted every 5 minutes
*/5 * * * * /path/to/script.shExecuted every Monday at 8 a.m
0 8 * * 1 /path/to/script.shView recent login history
View user login history
lastView login failure records
sudo lastbCheck the user's last login time
lastlogView open files
View files opened by the system
sudo lsofView files opened by the specified process
sudo lsof -p <pid>View which processes use the specified file
sudo lsof <file>Check the usage of the specified port
sudo lsof -i :<port>View hardware information
View PCI devices
lspciView USB devices
lsusbView Block Devices
lsblkView memory hardware information
sudo dmidecode --type memoryView BIOS information
sudo dmidecode --type biosView the system hardware overview
sudo lshw -shortShutdown and restart
immediate shut down
sudo shutdown -h nowYou can also use:
sudo poweroffimmediately restart
sudo rebootShut down in 10 minutes
sudo shutdown -h +10Shut down at specified time
sudo shutdown -h 23:30Cancel scheduled shutdown
sudo shutdown -cCommon shortcut keys
| shortcuts | role |
|---|---|
Ctrl + C | Terminate current command |
Ctrl + Z | Pause current process |
Ctrl + D | Exit the current Shell or send EOF |
Ctrl + L | clear screen |
Ctrl + A | Move to front of line |
Ctrl + E | Move to end of line |
Ctrl + U | Delete all content before the cursor |
Ctrl + K | All content after deleting the cursor |
Ctrl + W | Delete the word before the cursor |
Ctrl + R | Search history command |
Tab | autocomplete |
↑ / ↓ | Browse history command |
Common command combinations
View disk space
df -ThView the space occupied by each directory and sort it
du -sh * | sort -hfinding large files
find / -type f -size +1G 2>/dev/nullView the processes with the highest memory usage
ps aux --sort=-%mem | headView the processes that use the most CPU
ps aux --sort=-%cpu | headCheck whether the specified port is occupied
sudo ss -tulpn | grep :<port>Check whether the specified program is running
pgrep -a <process-name>View logs in real time
tail -f <log-file>View the service log of the last 100 lines
journalctl -u <service> -n 100View service logs in real time
journalctl -u <service> -fFind a file that contains the specified text
grep -rn "<keyword>" <directory>View the current server IP address
ip -br addrView default gateway
ip route | grep defaultCheck the basics of CPU, memory and disks
lscpu
free -h
df -ThView disk, partition, and LVM status
lsblk
sudo pvs
sudo vgs
sudo lvs
df -ThCommon troubleshooting processes
When services on the server cannot be accessed normally, you can quickly troubleshoot them in the following order:
flowchart TD
A[服务无法访问] --> B[检查服务状态]
B --> C[检查服务日志]
C --> D[检查进程]
D --> E[检查监听端口]
E --> F[检查本机网络]
F --> G[检查远程连通性]
G --> H[检查磁盘和内存]
1. Check service status
systemctl status <service>2. View service logs
journalctl -u <service> -n 1003. viewing process
pgrep -a <process-name>4. View listening ports
sudo ss -tulpn5. Check local IP and routing
ip addr
ip route6. test network connectivity
ping -c 4 <host>7. Check system resources
free -h
df -Th
uptimeWhen actually troubleshooting problems, you should usually first confirm whether "the service is running", then confirm whether "the port is listening", and finally check the firewall, network, DNS and system resources. This makes it easier to locate problems than directly modifying the configuration.
If you enjoyed this, leave a comment~