Blog / Linux/ Essential Linux Commands for System Administration

Essential Linux Commands for System Administration

运维常用Linux命令

This article compiles essential Linux commands for system administration, covering file operations, text processing, process management, and other core tasks. It serves as a quick reference for daily operations.

File and Directory Operations

Commands for navigating, viewing, and managing files and directories.

cd (Change Directory)

Changes the current working directory.

cd /home        # Enter '/home' directory
cd ..           # Go up one directory level
cd ../..        # Go up two directory levels
cd              # Go to the current user's home directory
cd ~user1       # Go to user1's home directory
cd -            # Return to the previous directory

pwd (Print Working Directory)

Displays the absolute path of the current directory.

$ pwd
/home/user

ls (List Directory Contents)

Lists files and subdirectories.

ls              # List contents of current directory
ls -l           # Long listing (permissions, owner, size, etc.)
ls -a           # List all files, including hidden ones (starting with .)
ls -R           # Recursively list subdirectory contents
ls [0-9]*       # List files/directories whose names start with a digit

cp (Copy)

Copies files or directories.

cp source_file dest_file          # Copy a file
cp -r source_dir dest_dir        # Recursively copy a directory (common)
cp -a source dest                # Archive copy, preserving all attributes
cp -i source dest                # Prompt before overwriting
cp -u source dest                # Copy only if source is newer

mv (Move/Rename)

Moves or renames files/directories.

mv old_name new_name             # Rename a file or directory
mv file /target/dir/            # Move a file to a target directory
mv -i source dest               # Prompt before overwriting
mv -u source dest               # Move only if source is newer

rm (Remove)

Deletes files or directories. Use with caution, especially recursive deletion.

rm file                         # Delete a file
rm -r directory                 # Recursively delete a directory (dangerous)
rm -f file                      # Force delete, ignore missing files, no prompt
rm -i file                      # Interactive delete, confirm before removal

Viewing File Content

Commands for viewing and browsing text files.

cat (Concatenate and Display)

Outputs entire file content to standard output.

cat file.txt                    # Display entire file content
cat -n file.txt                 # Display with line numbers
tac file.txt                    # Display content in reverse (last line first)

more / less (Paged Viewing)

View long files page by page. less is more powerful, supporting forward/backward navigation.

more long_file.log              # View with forward-only paging
less long_file.log              # View with full navigation and search

head / tail (View Beginning/End)

View the beginning or end of a file.

head -n 20 file.log             # View first 20 lines
tail -n 50 file.log             # View last 50 lines
tail -f /var/log/app.log        # Follow (monitor) new content in real-time (common)
tail -n +100 file.log           # Display from line 100 to end

Combination example: View lines 1000 to 3000 of a file.

cat filename | head -n 3000 | tail -n +1000
# Or
sed -n '1000,3000p' filename

File Search

Find files in the filesystem.

find (Find Files)

Powerful real-time file search tool.

find / -name "myfile.txt"       # Search from root by name
find /home -user username       # Find files owned by a user
find /var/log -type f -mtime -7 # Find regular files modified within 7 days in /var/log
find /tmp -size +100M           # Find files larger than 100MB in /tmp
find . -name "*.log" -exec rm {} ; # Find and delete all .log files (dangerous)

which / whereis (Find Commands)

Locate executable commands.

which ls                        # Show full path of ls command
whereis python                  # Show binary, source, and manual page locations

File Permissions and Ownership

Manage access permissions for files and directories.

chmod (Change Mode)

Modify permissions using symbolic (u/g/o/a, +/-, r/w/x) or numeric (octal) modes.

chmod u+x script.sh             # Add execute permission for owner
chmod 755 directory             # Set directory permissions to rwxr-xr-x
chmod go-w file.txt             # Remove write permission for group and others

chown / chgrp (Change Owner/Group)

Change file owner and group.

chown user:group file           # Change both owner and group
chown -R user:group /project    # Recursively change owner/group for directory
chgrp developers file           # Change file group only

Text Processing

Filter, transform, and analyze text content.

grep (Global Regular Expression Print)

Search for lines matching a pattern.

grep "error" /var/log/syslog    # Search for lines containing "error"
grep -r "TODO" ./src            # Recursively search all files in current directory
grep -v "^#" config.conf        # Show all non-comment lines (not starting with #)
grep -E "[0-9]{3}-[0-9]{4}" file # Use extended regex to match phone number pattern

sed (Stream Editor)

Filter and transform text.

sed 's/old/new/g' file          # Replace all 'old' with 'new' in file
sed '/^$/d' file                # Delete all empty lines in file
sed -n '5,10p' file             # Print only lines 5 to 10 of file

sort / uniq (Sort and Deduplicate)

Sort text lines and remove duplicates.

sort file.txt                   # Sort lines of file
sort -u file.txt                # Sort and remove duplicates
uniq sorted_file.txt            # Report or omit repeated lines (usually after sorting)
uniq -c sorted_file.txt         # Count occurrences of duplicate lines

paste / comm (Merge and Compare)

paste file1 file2               # Merge two files side-by-side (column merge)
comm -12 file1 file2            # Output intersection of two sorted files
comm -3 file1 file2             # Output lines unique to each file (symmetric difference)

Archiving and Compression

Archive and compress files and directories.

tar (Tape Archive)

Create archive files, optionally with gzip/bzip2 compression.

# Create compressed archive (common combinations)
tar -czvf archive.tar.gz /path/to/dir   # Compress with gzip
# Extract archive
tar -xzvf archive.tar.gz -C /target/dir # Extract to target directory
# List archive contents
tar -tzvf archive.tar.gz

gzip / bzip2 / xz (Compression Tools)

gzip file                        # Compress file, producing file.gz
gunzip file.gz                   # Decompress .gz file
bzip2 file                       # Compress with bzip2, producing file.bz2
xz file                          # Compress with xz (often higher compression ratio)

zip / unzip

zip -r archive.zip dir/          # Recursively compress directory
unzip archive.zip                # Extract zip file
unzip -l archive.zip             # List contents of zip file

System Shutdown and Reboot

shutdown -h now                  # Shut down immediately
shutdown -r +10 "System rebooting in 10 minutes" # Reboot in 10 minutes with message
shutdown -c                      # Cancel scheduled shutdown/reboot
reboot                           # Reboot immediately
poweroff                         # Power off immediately (some systems)
logout                           # Log out current session
time command                     # Measure command execution time

Process Management

View and manage system processes.

ps (Process Status)

ps aux                          # View detailed info for all processes (common)
ps -ef                          # List all processes in full format
ps aux | grep nginx             # Find processes related to nginx

top / htop (Dynamic Process View)

Real-time display of system processes and resource usage. htop is an enhanced, more interactive version of top.

top                             # Start dynamic process viewer
htop                            # Feature-rich process viewer (may require installation)

kill / killall / pkill (Terminate Processes)

Send signals to processes. Default is TERM (15) to request termination.

kill 1234                       # Request termination of process with PID 1234
kill -9 1234                    # Force kill process (SIGKILL, cannot be caught/ignored)
killall -9 process_name         # Force kill all processes named process_name
pkill -f "python script.py"     # Kill processes by matching full command line

jps (Java Process Status)

View Java processes (requires JDK).

jps                             # List Java processes and their PIDs
jps -l                          # Output full package name of main class

netstat / ss (Network Connections and Ports)

View network connections, routing tables, interface statistics. ss is a modern, faster replacement for netstat.

netstat -tunlp | grep :80       # Find process listening on port 80
ss -tlnp                        # List all listening TCP ports and processes (faster)

Mastering these fundamental commands will significantly improve efficiency in Linux administration. Practice them in real scenarios and use man [command] or [command] --help to consult detailed manuals.

Post a Comment

Your email will not be published. Required fields are marked with *.