Quick Start – Summary of Common Linux Commands

Linux Server System Information

# Display basic system information
uname -a
# View kernel version
uname -r

# Display information about the distribution - detailed information about the operating system
lsb_release -a
# Linux version
cat /etc/issue
cat /etc/os-release
more /etc/redhat-release
hostnamectl
cat /proc/version

# CPU information
cat /proc/cpuinfo
more /proc/cpuinfo | grep "model name"
# CPU bitness
getconf LONG_BIT

# Memory information
grep memtotal /proc/meminfo
free -m

# View timezone
date -R

# Installed packages
rpm -qa | wc -l
yum list installed | wc -l

# Command help information query
man

# Display online logged-in users
who

# Display the identity of the current user
whoami

# Display the processes consuming the most resources in the current system
top

# Display the instantaneous process status
ps

# Display disk space usage of the file system
df

# Display the total disk space used by a specified file (directory)
du

# Display current memory and swap space usage
free

# Display network interface information
ifconfig
cat /etc/sysconfig/network

# Test network connectivity
ping

# Display network status information
netstat

# View software installation directory
whereis

# View software execution path
which

# Domain name resolution
nslookup

# Clear screen
clear

# Kill process
kill

# Shutdown server
shutdown -h now
shutdown -r now

Folder Structure Explanation

# In Linux, everything is a file (software, hardware, documents, etc.)
# Common directories:
  Directory Name         Description
  /          Linux system root directory

  /bin      Executable files needed for system startup (binary)

  /boot           Stores some core files used to boot Linux

  /dev      Device file directory (external devices of Linux)

  /etc      Directory for operating system configuration files (firewall, startup items)

  /home        Directory for storing user information, the default working directory for users

  /lib            Library files that store the most basic dynamic linking shared libraries, similar to DLL files in Windows

  /lost+found     Stores some files after an illegal system shutdown

  /media          Automatically recognized devices, such as USB drives, CD-ROMs, etc.

  /mnt            Temporarily mount other file systems

  /opt            Optional directory for additional software installations

  /proc           A pseudo-filesystem (virtual filesystem) that stores a series of special files representing the current kernel's running state; this directory is a virtual directory mapped to system memory, allowing direct access to system information. The contents of this directory are not on the hard disk but in memory, and some files can be modified directly, such as blocking ping commands to prevent others from pinging your machine.

  /root           The home directory for the system administrator, also known as the superuser.

  /sbin           Superuser Binaries (binary files for superuser) directory, storing system management programs used by the system administrator.

  /usr      usr stands for Unix Shared Resources, a very important directory where many user applications and files are stored, similar to the Program Files directory in Windows.

  /usr/src        Default directory for kernel source code.

  /var      Contains files that change during normal operation: spool files, log files, lock files, temporary files, and page format files (log files).

Linux Directory and File Operation Commands

# View current directory
pwd

################################
cd     Open directory
cd.     Open subdirectory
cd..    Open parent directory

################################
ls -a    View files in the directory (including hidden ones)
ll     Display a list of files in the directory in columns

################################
mkdir      DirectoryName  Create a directory

rm -rf   Delete file or directory
rm -rf /   Absolute path
rm -ri   Prompt user before deleting files

################################
touch      FileName Create an empty file
echo     Generate a file with content

################################
cp    Copy file command
cp -rf / SourceAbsolutePath / DestinationAbsolutePath

mv    Move file or rename file
mv / OldPathName / NewPathName
mv / SourceAbsolutePath / DestinationAbsolutePath
clear   Clear screen

################################
# Find file
find -name     FileName

################################
# Display content of text files
[cat, tac, more, tail] 

head      Display content from the start of the file

head -n    Display the first n lines of a specified file. For example: head -3 shadow
      
cat        FileName: View all content

tail    Display content from the end of the file

tail -f    Dynamically load the content of a file. For example: tail -f message: used to monitor log files
      
tail -n    View the last n lines of a specified file

Linux Permission Management

# (User/User Group)

 User:  Refers to the actual operator of the operating system
 User Group: A collection of users with similar characteristics
 UID:  Unique identifier for the user
 GID:  Unique identifier for the user group
 root user: The user with the highest permissions in the Linux system

#######################################
# Switch to specified user
su [Username]

# View current logged-in user
whoami

# View groups the current user belongs to
groups

# View current user's UID and GID
id

# Add user
useradd [Username]

# Add user and specify UID
useradd -u [UID]

#######################################
/etc/passwd  This file stores user information
/etc/group  This file stores group information

# Modify user password
passwd [Username]

# Delete user
userdel [Username]

# Modify user login name
usermod -l [NewUsername] [OldUsername]

# Modify user group
usermod -g [NewGroupName] [Username]

# Add group
groupadd [GroupName]

# Add group and specify GID
groupadd -g [GroupGID] [GroupName]

# Example: groupadd -g 601 test1

Linux User Permissions

# Description: d rwx r-x r-x 2   root   root  4096 Sep 23 2011 etc

 -d   :   d indicates a directory rather than a file
 -rwx  :   The owner has read, write, and execute permissions
 -r-x :   Group users have read and execute permissions, but no write permissions
 -r-x  :   Other group users have read and execute permissions, but no write permissions

# Permission modes:
  u, g, o, a : Owner, Group users, Other users, All users

  -, +, =    : Grant, Remove, Set

  r, w, x    : Read, Write, Execute permissions

# Numeric mode
# Use a 3-digit decimal number to represent permission operations
   r = 4
   w = 2
   x = 1

 r+w+x=7    r+x=5      w+x=3
 Owner      Group users    Other users

# Numeric representation of permission combinations:

 ---:0
 --x:1
 -w-:2
 -wx:3
 r--:4
 r-x:5
 rw-:6
 rwx:7

############################ chmod ##############################
# chmod (change mode) command is used to change file or directory permissions

chmod [options] mode filename

# For example:
chmod u+x filename
chmod U+X,G+W filename
chmod g-w filename

# Set permissions to rwxr-xr--:
chmod 754 filename

# -R: Recursively change permissions of the directory and its contents
chmod -R 755 directoryname

############################ chown ##############################
# chown (change owner) command is used to change the owner and/or group of a file. Basic syntax:

chown [options] user:group filename

# -R: Recursively change the owner and group of the directory and its contents
chown -R newuser:newgroup filename

Common Settings

Firewall firewalld and port settings

# Firewall firewalld
systemctl start firewalld   Start
systemctl status firewalld  Status
systemctl stop firewalld    Stop
systemctl disable firewalld Disable firewall startup on boot

firewall-cmd --reload       Restart firewall

# Open specified port
firewall-cmd --zone=public --add-port=80/tcp --permanent
# Remove specified port
firewall-cmd --zone=public --remove-port=2375/tcp --permanent

# Note: The firewall depends on the local Python version; if you upgrade the Python version, you need to modify the firewall configuration file
# vim /usr/bin/firewall-cmd, change #!/usr/bin/python -Es to #!/usr/bin/python2.7 -Es
# vim /usr/sbin/firewalld, change #!/usr/bin/python -Es to #!/usr/bin/python2.7 -Es

Ports

# View port status
netstat -tunlp

netstat -tunlp | grep port_number
# netstat -ntulp | grep 80   // View all usage of port 80

Processes

# View port status
ps -aux
ps -ef

# View specific process
ps pid

Monitoring IO, CPU, Memory, Disk


############## View overall situation ##########
top
htop

# The top command dynamically views a process's memory usage, set to delay 1s, default is delay 3s
top -d 1 -p pid [,pid ...]

# pmap command statically views a process's memory usage
# The pmap command can display the amount of memory used by one or more processes. You can use this tool to understand how much memory a process on the server has allocated and determine if it is causing memory bottlenecks. To get more detailed information, use the pmap -d option.
pmap pid

################# Disk IO #################
iostat -xd

################# Network IO #################
iftop -n

ifstat

dstat -nt

################# Disk Capacity #################
df -h

################# Memory #################
free -m

File Compression and Decompression


#######################################################################
################################ Compression #########################
#######################################################################

# tar is a tool for creating and processing archive files, usually used with gzip or bzip2.

# Create .tar.gz file
# Compress a single file
tar -zcvf archive.tar.gz /path/to/file
# Compress a directory
tar -zcvf archive.tar.gz /path/to/directory

c:Create a new archive file.
z:Use gzip compression.
v:Display files during processing.
f:Specify the name of the archive file.

# Create .tar.bz2 file:
tar -cjvf archive.tar.bz2 /path/to/directory

j:Use bzip2 compression.

#######################################################################
################################ Decompression #########################
#######################################################################

# Decompress .tar.gz file
tar -zxvf archive.tar.gz

# Decompress .tar.bz2 file
tar -xjvf archive.tar.bz2

#######################################################################
######################## gzip and gunzip #############################
#######################################################################

# Compress file
gzip filename

# Decompress file
gunzip filename.gz

gzip -d filename.gz

Disk Settings

# View overall disk status
df -h

# View space usage of folders
du -sh *
du -sh /path
# Sort

du -ah /path/to/directory | sort -rh

# View disk mount status
lsblk
lsblk -f
fdisk -l

# Normal unmount, unmount the disk corresponding to /home/data
umount /home/data
# Force unmount
umount -l /home/data

# Assuming you have increased the size of the /dev/sdb disk in the cloud service provider (e.g., AWS, Azure), now you need to partition and adjust the file system in the system
# Partition the disk using fdisk or parted tools to delete and recreate partitions
# Warning: Be very careful when using these tools, as incorrect operations may lead to data loss

# https://www.ywbj.cc/?p=712
# https://blog.csdn.net/qq_39766779/article/details/140787071

# Check physical volume (PV) usage
fdisk 
 m    Get help information
 n    Create new partition
 Choose partition type p for primary partition, e for extended partition
 Specify partition number (if this is the first partition, usually 1)
  Specify the starting and ending sectors or specify partition size with +SIZEM or +SIZEG (e.g., +500M for a 500MB partition)
  Enter w to write changes and exit

# 1. Start fdisk tool
sudo fdisk /dev/nvme0n1

# 3. Use growpart to extend the partition
sudo growpart /dev/xvda 1

# 4. After partition adjustment, extend the file system to use the new disk space

# Extend ext4 file system 
# Check and repair file system (optional)
 sudo e2fsck -f /dev/xvda1
# Extend file system
 sudo resize2fs /dev/xvda1

################################################################
##################### Different file systems have different expansion commands ################

# For ext4, ext3, or ext2 file systems, use resize2fs command
sudo resize2fs /dev/xvda1

# For XFS file systems, use xfs_growfs command. Note that XFS file systems must be mounted to be extended.
sudo xfs_growfs /mount/point

# For Btrfs file systems, use btrfs filesystem resize command
sudo btrfs filesystem resize max /mount/point

Network Related

# Configure static IP

### In CentOS or RHEL systems, network interface configurations are usually stored in /etc/sysconfig/network-scripts/ifcfg-<interface> file.
### If ens160 is your network interface name, the configuration file path for that interface is /etc/sysconfig/network-scripts/ifcfg-ens160.

# Edit configuration file

 sudo vi /etc/sysconfig/network-scripts/ifcfg-ens160

# Content

 TYPE=Ethernet
 BOOTPROTO=static
 NAME=ens160
 DEVICE=ens160
 ONBOOT=yes
 IPADDR=192.168.179.137
 NETMASK=255.255.255.0
 GATEWAY=192.168.179.1
 DNS1=8.8.8.8
 DNS2=8.8.4.4

 Configuration item description:
  TYPE: Type of network interface. Ethernet indicates this is a wired network interface.
  BOOTPROTO: Set to static indicates using static IP address configuration. If you use DHCP, it should be set to dhcp.
  NAME: Name of the network interface (ens160).
  DEVICE: Device name of the network interface (ens160).
  ONBOOT: Whether to enable this interface at system startup. Set to yes to enable this interface at startup.
  IPADDR: Configured static IP address (e.g., 192.168.179.137).
  NETMASK: Subnet mask (usually 255.255.255.0, if it is a /24 subnet).
  GATEWAY: IP address of the default gateway (e.g., 192.168.179.1).
  DNS1 and DNS2: Configure DNS server addresses (e.g., Google's public DNS addresses 8.8.8.8 and 8.8.4.4, you can also use other DNS services).

# Restart network service
sudo systemctl restart network
sudo systemctl restart NetworkManager

# Verify network configuration
ip addr show ens160
</interface>

Software Installation

rpm, yum, and apt are tools related to the Linux package management system, performing similar functions in different Linux distributions but with some key differences.

rpm (Red Hat Package Manager): rpm is the package management tool used by Red Hat and its derivative distributions (such as CentOS, Fedora, etc.). Main functions: rpm is mainly used to install, upgrade, uninstall, and query packages. It manages individual packages without addressing dependencies between packages.

yum: yum (Yellowdog Updater, Modified) is a package management tool based on rpm, designed to simplify the use of rpm and resolve dependencies between packages. Main functions: yum can automatically resolve dependencies by downloading and installing packages from specified repositories. It can handle dependencies, upgrade and uninstall packages, and can cache packages locally for efficiency.

apt (Advanced Package Tool): apt is the package management tool for Debian and its derivative distributions (such as Ubuntu). Main functions: apt provides a set of advanced tools for managing packages in Debian systems. apt automatically resolves dependencies by downloading and installing packages from specified repositories, similar to yum’s functionality. apt can also upgrade all packages in the system.

Supported distributions: rpm is mainly used for Red Hat and its derivative distributions. yum is an extension based on rpm, specifically designed for Red Hat systems. apt is mainly used for Debian and its derivative distributions.

Dependency resolution: rpm itself does not resolve dependencies, and users typically need to resolve dependency issues manually. Both yum and apt have the capability to automatically resolve dependencies, making it more convenient to install and upgrade packages.

Software repositories: rpm operates on local package files rather than managing through software repositories. yum and apt use software repositories to manage the installation, upgrade, and uninstallation of packages through online repositories. Overall, these tools provide convenient package management methods for Linux systems, with yum and apt being more advanced and user-friendly, especially in handling dependencies.

Package Management

# Ubuntu/Debian systems

 sudo apt update

# CentOS/RHEL systems

 sudo yum install epel-release 

Installation Methods

# 1. tar decompression installation

  - Installation package formats: tar, tar.gz, tar.bz
  - Install software package: tar -zxvf [package_name]

# 2. rpm direct installation

  - Installation package format: rpm
  - Install software package: rpm -ivh package_path
  - Uninstall software package: rpm -e full_package_name

# 3. yum online installation

  - Install software package: yum -y install subversion
  - Uninstall software package: yum -y remove subversion

Installation Example

Install JDK

# Update packages
sudo yum update

# Install
sudo yum install java-1.8.0-openjdk
# sudo yum install java-1.8.0-openjdk-devel
# sudo yum install java-17-openjdk-devel

java -version

Install Nginx

sudo yum update
sudo yum install nginx
sudo systemctl start nginx

Install Apache Tomcat

 Download address: archive.apache.org

 Steps:
  1. Download Tomcat

  2. Decompress installation package
   -tar -zxvf tomcat7.0.tar.gz -C /usr/build     【C capitalized, followed by the decompression path】

  3. OK

  4. Start in the bin directory
   -sh startup.sh

  5. Open port
   -  First close the firewall
   -  Check IP
   -  At this point, you can access it from other hosts by visiting the IP address and port.

Swap Partition Usage

# 1. Create swap partition
sudo dd if=/dev/zero of=/var/swapfile bs=1M count=2048
sudo dd if=/dev/zero of=/var/swapfile bs=1G count=8
sudo fallocate -l 8G /var/swapfile

# 2. Authorize file
sudo chmod 600 /var/swapfile

# 3. Use mkswap command to create swap partition from the newly created file
sudo mkswap /var/swapfile

# 4. Enable swap
sudo swapon /var/swapfile

## Disable swap 
 sudo swapoff /var/swapfile   
## Note: To make it permanent, edit /etc/sysctl.conf file
 echo "/var/swapfile swap swap defaults 0 0" >> /etc/fstab

# 5. View partition
swapon -s
swapon --show

#######
# Set swappiness value: swappiness is a Linux kernel parameter that controls the system's tendency to use swap instead of killing processes when memory is low. You can adjust the swappiness value using the sysctl command. For example, set the swappiness value to 60

sudo sysctl vm.swappiness=60

# Release server cache

sync && echo 3 > /proc/sys/vm/drop_caches

# Or

sudo sysctl -w vm.drop_caches=3

## Support docker

# Edit grub configuration: Open /etc/default/grub file

# Linux buff/cache too high consuming physical memory

The value of drop_caches can be a number between 0-3, representing different meanings:
        0: Do not release (default value of the system)
        1: Release page cache
        2: Release dentries and inodes
        3: Release all caches
 echo 3 > /proc/sys/vm/drop_caches to clear buff/cache, the memory of this device has returned to normal

Acknowledgments

I hope this article is helpful to you! If you have any questions, feel free to discuss. For more content, please follow the [Xiao Wu Programming Room] public account. I also hope you can like and share to support; your likes and support are the greatest encouragement for the editor. Thank you for your attention and support from Xiao Wu Programming Room. 🎉🎉🎉🚀🚀🚀

Leave a Comment