0% found this document useful (0 votes)
15 views28 pages

Linux Commands: A Practical Guide

The document provides a comprehensive guide to Linux commands, covering various topics such as file and directory management, process management, disk management, and networking. Each section includes practical examples of commands and their options, making it a useful resource for both beginners and experienced users. The content is structured to facilitate easy navigation through different command functionalities.

Uploaded by

Manohar Sankar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views28 pages

Linux Commands: A Practical Guide

The document provides a comprehensive guide to Linux commands, covering various topics such as file and directory management, process management, disk management, and networking. Each section includes practical examples of commands and their options, making it a useful resource for both beginners and experienced users. The content is structured to facilitate easy navigation through different command functionalities.

Uploaded by

Manohar Sankar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Linux Commands: Explanation and Practical Examples

Davoud Azari
Contents
Linux Commands: Explanation and Practical Examples ........................................................................ 1
1. File and Directory Management .................................................................................................... 3
2. File Viewing and Editing ................................................................................................................ 5
3. Process Management........................................................................................................................ 6
4. Disk Management ............................................................................................................................. 8
5. Networking........................................................................................................................................ 9
6. User and Group Management ........................................................................................................ 11
7. System Information and Monitoring .............................................................................................. 12
8. Archiving and Compression ......................................................................................................... 13
9. Package Management (Depends on Distribution) .......................................................................... 14
10. System Services and Daemon Management ............................................................................. 16
11. Scheduling Tasks ......................................................................................................................... 17
12. File Permissions and Security .................................................................................................... 17
13. System Backup and Restore ....................................................................................................... 18
14. System Diagnostics and Troubleshooting ................................................................................. 19
15. Networking & Remote Management ......................................................................................... 21
16. Text Processing Utilities ............................................................................................................. 23
17. System Shutdown and Reboot ................................................................................................... 25
18. File System Mounting and Management .................................................................................. 25
19. Filesystem Permissions and Security......................................................................................... 26
1. File and Directory Management

 ls – List directory contents:

ls
ls -l # detailed list
ls -a # includes hidden files
ls -h # human-readable file sizes
ls -R # recursive listing
ls -S # sort by file size
ls -t # sort by modification time

 cd – Change directory:

cd /path/to/directory
cd .. # move up one directory
cd ~ # go to home directory
cd - # go to previous directory

 pwd – Print working directory:

pwd

 cp – files and directories:

cp [Link] /path/to/destination
cp -r folder1 /path/to/destination # directory recursively
cp -i [Link] /path/to/destination # prompt before overwriting
cp -u [Link] /path/to/destination # only if source is newer
cp -v [Link] /path/to/destination # verbose output

 mv – Move or rename files and directories:

mv [Link] /path/to/destination # move file


mv [Link] [Link] # rename file
mv -i [Link] /path/to/destination # prompt before overwriting
mv -u [Link] /path/to/destination # move only if source is newer

 rm – Remove files or directories:

rm [Link]
rm -r directory_name # remove directory recursively
rm -f [Link] # force remove, skip confirmation
rm -i [Link] # prompt before removing
rm -v [Link] # verbose output

 mkdir – Make directories:

mkdir new_directory
mkdir -p /path/to/directory # create parent directories if not exist
mkdir -v new_directory # verbose output
 rmdir – Remove empty directories:

rmdir directory_name
rmdir -v directory_name # verbose output

 touch – Change file timestamps or create empty files:

touch [Link] # create empty file if not exists


touch -c [Link] # do not create file if it does not exist
touch -t 202502191210.30 [Link] # set specific timestamp

 find – Search for files in a directory hierarchy:

find /path/to/directory -name "file*.txt"


find /path/to/directory -type f # find files only
find /path/to/directory -type d # find directories only
find /path/to/directory -size +100M # find files larger than 100MB
find /path/to/directory -mtime -7 # files modified in the last 7 days
find /path/to/directory -exec rm {} \; # find and delete files

 locate – Find files by name:

locate filename
locate -i filename # case insensitive search

 tree – Display directories in a tree-like format:

tree
tree -L 2 # limit depth to 2 levels
tree -d # list directories only
tree -f # show full path of files

 chmod – Change file permissions:

chmod 755 [Link] # owner can read/write/execute, others can


read/execute
chmod +x [Link] # add execute permission
chmod -R 755 directory # apply recursively
chmod u+x [Link] # add execute permission to the user
chmod g-w [Link] # remove write permission from the group

 chown – Change file owner and group:

chown user:group [Link]


chown -R user:group directory # recursively change owner and group

 chgrp – Change group ownership:

chgrp group_name [Link]


chgrp -R group_name directory # recursively change group ownership
 stat – Display file or file system status:

stat [Link]

2. File Viewing and Editing

 cat – Concatenate and display file content:

cat [Link]
cat -n [Link] # number the lines
cat -b [Link] # number non-blank lines only
cat -A [Link] # show all control characters

 tac – Concatenate and display file content in reverse:

tac [Link]

 more – View file content interactively (page by page):

more [Link]
more +10 [Link] # start viewing from line 10

 less – View file content interactively (scrollable):

less [Link]
less +G [Link] # go to end of file
less +/pattern [Link] # search for pattern

 head – Output the first part of a file:

head [Link]
head -n 20 [Link] # first 20 lines
head -c 50 [Link] # first 50 bytes

 tail – Output the last part of a file:

tail [Link]
tail -f [Link] # follow file as it's being updated
tail -n 20 [Link] # last 20 lines
tail -c 100 [Link] # last 100 bytes

 nano – Text editor (terminal-based):

nano [Link]
nano -w [Link] # disable line wrapping
nano -v [Link] # start in view-only mode

 vim / vi – Advanced text editors:

vim [Link]
vi [Link]
vim -y [Link] # read-only mode
vim -R [Link] # open in read-only mode

 emacs – Text editor:

emacs [Link]
emacs -nw [Link] # start in terminal mode (no GUI)

 grep – Search text using patterns:

grep "pattern" [Link]


grep -i "pattern" [Link] # case insensitive
grep -r "pattern" /path/to/dir # search recursively
grep -v "pattern" [Link] # exclude matching lines
grep -l "pattern" *.txt # show filenames containing pattern

 sed – Stream editor for filtering and transforming text:

sed 's/old/new/g' [Link] # replace 'old' with 'new' in the file


sed -i 's/old/new/g' [Link] # in-place edit
sed '1,5d' [Link] # delete lines 1 to 5

 awk – Pattern scanning and processing language:

awk '{print $1}' [Link] # print the first column of each line
awk -F, '{print $1}' [Link] # specify a delimiter (comma)

 cut – Remove sections from each line of files:

cut -d',' -f1 [Link] # extract first field of CSV file


cut -f1-3 [Link] # extract fields 1 to 3

 sort – Sort lines of text files:

sort [Link]
sort -r [Link] # reverse order
sort -n [Link] # numerical sort

 uniq – Report or omit repeated lines:

uniq [Link]
uniq -c [Link] # count occurrences of each line
uniq -d [Link] # show only duplicate lines

3. Process Management

 ps – Report a snapshot of current processes:

ps
ps -e # list all processes
ps -ef # full-format listing
ps -aux # user-oriented format
ps -u user # processes by specific user

 top – Display Linux tasks:

top
top -u user # show processes for a specific user
top -d 5 # update every 5 seconds
top -p pid # monitor specific process ID

 htop – Interactive process viewer (advanced top):

htop
htop -u user # show processes of a specific user
htop -d 5 # set refresh delay

 kill – Send a signal to a process, typically to terminate:

kill pid # terminate process by PID


kill -9 pid # force kill (SIGKILL)
kill -SIGTERM pid # send specific signal

 killall – Terminate processes by name:

killall process_name # terminate all processes by name


killall -9 process_name # force kill all processes

 bg – Resume a suspended job in the background:

bg job_number # resume a specific job


bg %1 # resume the first job

 fg – Bring a job to the foreground:

fg job_number # bring a specific job to the foreground


fg %1 # bring the first job to the foreground

 jobs – List active jobs:

jobs
jobs -l # list jobs with PID

 nice – Run a program with modified scheduling priority:

nice -n 10 command # run a command with lower priority


nice -n -10 command # run a command with higher priority

 renice – Alter priority of running processes:


renice -n 10 -p pid # change priority of a process by PID
renice -n -10 -p pid # change priority to higher for a process

 uptime – Show how long the system has been running:

uptime

 time – Measure program running time:

time command

4. Disk Management

 df – Report file system disk space usage:

df
df -h # human-readable format
df -T # show file system type
df /path/to/directory # disk space of a specific directory

 du – Estimate file space usage:

du [Link] # space used by a file


du -sh /path # human-readable summary
du -a /path # show space used by all files
du -h /path # human-readable format

 fdisk – Partition table manipulator for Linux:

fdisk -l # list all partitions


fdisk /dev/sda # manipulate partitions on /dev/sda

 lsblk – List information about block devices:

lsblk
lsblk -f # show filesystem type
lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT # custom output

 mount – Mount a file system:

mount /dev/sda1 /mnt # mount device to /mnt


mount -t ext4 /dev/sda1 /mnt # specify filesystem type

 umount – Unmount a file system:

umount /mnt
umount /dev/sda1

 parted – A partition manipulation program:


parted /dev/sda
parted -l # list partitions
parted /dev/sda mkpart primary ext4 1GB 10GB # create a partition

 mkfs – Create a file system:

mkfs.ext4 /dev/sda1 # create ext4 file system


[Link] /dev/sda1 # create XFS file system

 fsck – File system consistency check and repair:

fsck /dev/sda1 # check and repair the file system


fsck -f /dev/sda1 # force check even if the system thinks it's
clean

 blkid – Locate/print block device attributes:

blkid
blkid /dev/sda1 # get attributes for specific device

5. Networking

 ifconfig – Configure network interfaces:

ifconfig
ifconfig eth0 up # bring interface eth0 up
ifconfig eth0 down # bring interface eth0 down
ifconfig eth0 [Link] netmask [Link] # set IP and netmask
ifconfig -a # show all interfaces, even inactive ones

 ip – Show/manipulate routing, devices, and tunnels:

ip addr # show IP addresses


ip link # show network interfaces
ip route # show routing table
ip link set eth0 up # bring interface eth0 up
ip addr add [Link]/24 dev eth0 # assign IP address

 ping – Send ICMP Echo requests to network hosts:

ping [Link] # ping IP address


ping -c 4 [Link] # send 4 ICMP packets to [Link]
ping -i 0.5 [Link] # set interval between pings to 0.5 seconds

 netstat – Network statistics:

netstat # show network connections


netstat -tuln # show listening ports and associated processes
netstat -i # show network interface statistics
netstat -r # show routing table
 ss – Socket statistics (faster than netstat):

ss # display all sockets


ss -tuln # show listening TCP/UDP ports
ss -p # show process using the socket

 traceroute – Trace the route packets take to a network host:

traceroute [Link] # trace route to [Link]


traceroute -m 20 [Link] # set max hops to 20

 nslookup – Query Internet name servers interactively:

nslookup [Link] # look up the IP address for [Link]


nslookup [Link] # look up the domain for IP address [Link]

 dig – DNS lookup utility:

dig [Link] # query DNS records for [Link]


dig @[Link] [Link] # query DNS using a specific DNS server
dig +short [Link] # show only the IP address

 wget – Non-interactive network downloader:

wget [Link] # download a file


wget -c [Link] # continue a previously
interrupted download
wget -r [Link] # download a website recursively

 curl – Transfer data with URLs:

curl [Link] # fetch data from a URL


curl -O [Link] # download file
curl -I [Link] # show HTTP headers
curl -u user:password [Link] # use basic authentication

 scp – Secure copy files between hosts:

scp [Link] user@remote_host:/path/to/destination


scp -r folder user@remote_host:/path/to/destination # copy directory
recursively

 ssh – Secure shell for remote login:

ssh user@remote_host # login to a remote machine


ssh -p 2222 user@remote_host # specify a different port
ssh -i /path/to/private_key user@remote_host # use an SSH key for
authentication

 ftp – File Transfer Protocol client:


ftp [Link] # connect to FTP server
ftp> ls # list files in the FTP server directory
ftp> get [Link] # download a file from the server
ftp> put [Link] # upload a file to the server

6. User and Group Management

 useradd – Add a user to the system:

useradd newuser # create a new user


useradd -m -s /bin/bash newuser # create a user with home directory
and bash shell

 usermod – Modify a user account:

usermod -aG groupname username # add user to a group


usermod -s /bin/zsh username # change user shell

 userdel – Delete a user account:

userdel username # delete user account


userdel -r username # delete user and their home directory

 groupadd – Add a group to the system:

groupadd newgroup # create a new group

 groupdel – Delete a group:

groupdel groupname # delete group

 passwd – Change user password:

passwd username # change password for a user


passwd # change the current user's password

 chage – Change user password expiry information:

chage -l username # display password expiration info


chage -E 2025-12-31 username # set password expiration date

 whoami – Print the current logged-in user:

whoami

 who – Show who is logged in:

who
 w – Show who is logged in and what they’re doing:

 id – Display user and group information:

id username # display user and group IDs

 groups – Show user’s groups:

groups username # show the groups a user belongs to

7. System Information and Monitoring

 uname – Print system information:

uname # basic system info (kernel name)


uname -a # all system information
uname -r # kernel version
uname -m # machine hardware name

 hostname – Show or set the system’s hostname:

hostname # show the current hostname


hostname new-hostname # set the system hostname

 uptime – How long the system has been running:

uptime

 dmesg – Boot and system messages:

dmesg # display boot and system messages


dmesg | grep error # filter dmesg output for errors

 free – Display memory usage:

free # display memory usage


free -h # human-readable format
free -m # display in MB
free -g # display in GB

 top – Display Linux tasks:

top # display tasks


top -u user # show processes of a specific user
top -p pid # monitor a specific process by PID
top -d 5 # update every 5 seconds

 vmstat – Report virtual memory statistics:


vmstat # display virtual memory stats
vmstat 5 # update every 5 seconds

 lscpu – Display information about the CPU architecture:

lscpu # display CPU architecture details

 lsusb – List USB devices:

lsusb # list USB devices


lsusb -v # detailed information about USB devices

 lspci – List PCI devices:

lspci # list PCI devices


lspci -v # detailed information about PCI devices

 lshw – List hardware configuration:

lshw # list hardware configuration


lshw -short # show a summary of hardware
lshw -C network # show network devices only

8. Archiving and Compression

 tar – Archive files:

tar -cf [Link] /path/to/directory # create a tarball


tar -xf [Link] # extract tarball

o Compress files using gzip:

tar -czf [Link] /path/to/directory # create a gzipped


tarball
tar -xzf [Link] # extract gzipped tarball

 zip – Package and compress files into a ZIP archive:

zip [Link] file1 file2 file3 # create a zip archive


zip -r [Link] /path/to/directory # zip a directory recursively

 unzip – Extract files from a ZIP archive:

unzip [Link] # extract the zip archive


unzip [Link] -d /path/to/extract # extract to a specific
directory

 gzip – Compress files using the gzip algorithm:

gzip [Link] # compress a file


gzip -d [Link] # decompress a file

 gunzip – Decompress files compressed with gzip:

gunzip [Link] # decompress a file

 bzip2 – Compress files using the bzip2 algorithm:

bzip2 [Link] # compress a file


bzip2 -d [Link].bz2 # decompress a file

 bunzip2 – Decompress files compressed with bzip2:

bunzip2 [Link].bz2 # decompress a file

 xz – Compress files using the xz algorithm:

xz [Link] # compress a file


xz -d [Link] # decompress a file

 unxz – Decompress files compressed with xz:

unxz [Link] # decompress a file

9. Package Management (Depends on Distribution)

Debian-based (e.g., Ubuntu)

 apt-get – APT package handling utility:


o apt-get install <package> – Install a package:

sudo apt-get install package_name

o apt-get update – Update package list:

sudo apt-get update

o apt-get upgrade – Upgrade installed packages:

sudo apt-get upgrade

o apt-get remove <package> – Remove a package:

sudo apt-get remove package_name

 apt-cache – Query APT cache:


o apt-cache search <package> – Search for a package:
apt-cache search package_name

o apt-cache show <package> – Show package details:

apt-cache show package_name

Red Hat-based (e.g., CentOS, Fedora)

 yum – Package manager for RPM-based systems:


o yum install <package> – Install a package:

sudo yum install package_name

o yum update – Update installed packages:

sudo yum update

o yum remove <package> – Remove a package:

sudo yum remove package_name

 dnf – Next-generation package manager (Fedora, CentOS 8+):


o dnf install <package> – Install a package:

sudo dnf install package_name

o dnf update – Update installed packages:

sudo dnf update

o dnf remove <package> – Remove a package:

sudo dnf remove package_name

General Commands

 rpm – RPM package manager:


o rpm -i <[Link]> – Install an RPM package:

sudo rpm -i package_name.rpm

o rpm -e <package> – Remove an RPM package:

sudo rpm -e package_name

 dpkg – Debian package manager:


o dpkg -i <[Link]> – Install a Debian package:
sudo dpkg -i package_name.deb

o dpkg -r <package> – Remove a Debian package:

sudo dpkg -r package_name

10. System Services and Daemon Management

 systemctl – Control the systemd system and service manager:


o systemctl start <service> – Start a service:

sudo systemctl start service_name

o systemctl stop <service> – Stop a service:

sudo systemctl stop service_name

o systemctl restart <service> – Restart a service:

sudo systemctl restart service_name

o systemctl enable <service> – Enable a service to start on boot:

sudo systemctl enable service_name

o systemctl disable <service> – Disable a service from starting on boot:

sudo systemctl disable service_name

o systemctl status <service> – Check service status:

systemctl status service_name

 service – Older service management command (used in non-systemd systems):


o service <service> start – Start a service:

sudo service service_name start

o service <service> stop – Stop a service:

sudo service service_name stop

o service <service> restart – Restart a service:

sudo service service_name restart

o service <service> status – Check service status:


sudo service service_name status

11. Scheduling Tasks

 cron – Daemon for running scheduled commands:


o crontab -e – Edit cron jobs for the current user:

crontab -e

o crontab -l – List the current user’s cron jobs:

crontab -l

o crontab -r – Remove the current user's cron jobs:

crontab -r

 at – Run commands at a specified time:


o at 09:00 – Schedule a command to run at 09:00 AM:

at 09:00
# Enter command to execute at 09:00

 batch – Run commands when the system load is low:

batch
# Enter commands to run when system load is low

 sleep – Delay for a specified time:


o sleep 5s – Sleep for 5 seconds:

sleep 5s

12. File Permissions and Security

 chmod – Change file permissions:

chmod 755 [Link] # owner can read/write/execute, others can


read/execute
chmod +x [Link] # add execute permission
chmod -x [Link] # remove execute permission

 chown – Change file owner and group:

chown user:group [Link]

 chgrp – Change the group ownership of a file:


chgrp group_name [Link]

 umask – Set default permissions for new files:

umask 022 # set default permissions to rw-r--r--

 setfacl – Set file access control lists (ACL):

setfacl -m u:username:rwx [Link] # give user 'username'


read/write/execute permissions

 getfacl – Get file access control lists (ACL):

getfacl [Link]

 sudo – Execute a command as another user (usually root):

sudo command # execute command as root


sudo -u user command # execute command as specific user

 visudo – Edit the sudoers file safely:

sudo visudo # edit sudoers file with proper syntax checking

 passwd – Change a user’s password:

sudo passwd user # change password for specific user

 sudoers – Manage sudo access for users:

sudo visudo # add or modify sudo access for users

 gpasswd – Administer group password:

sudo gpasswd -a user group_name # add user to group

 ss – Display socket statistics (for secure network connections):

ss -tuln # display listening sockets

13. System Backup and Restore

 rsync – Remote file and directory synchronization:


o rsync -avz source/ destination/ – Synchronize files:

rsync -avz source/ destination/


o rsync -avz -e ssh source/ user@remote:/destination/ – Sync over SSH:

rsync -avz -e ssh source/ user@remote:/destination/

 cpio – Copy files to and from archives:

cpio -o < file_list > [Link] # create an archive


cpio -i < [Link] # extract files from an archive

 dd – Low-level copying and backup of entire filesystems:


o dd if=/dev/sda of=/path/to/[Link] – Backup a disk/partition:

dd if=/dev/sda of=/path/to/[Link]

o dd if=/path/to/[Link] of=/dev/sda – Restore a disk/partition:

dd if=/path/to/[Link] of=/dev/sda

14. System Diagnostics and Troubleshooting

 dmesg – Print the kernel ring buffer messages (system boot and hardware-related
messages):

dmesg
dmesg | grep error # filter for error messages
dmesg -T # show human-readable timestamps

 journalctl – Query and view logs from systemd’s journal:

journalctl
journalctl -xe # show detailed error messages
journalctl -u service_name # show logs for a specific service
journalctl -f # follow logs in real-time

 strace – Trace system calls and signals:

strace <command> # trace a specific command's system calls


strace -p <pid> # trace a specific process by PID
strace -f <command> # follow child processes

 lsof – List open files (useful for debugging):

lsof # list all open files


lsof /path/to/file # show processes using a specific file
lsof -i :80 # list processes using port 80

 vmstat – Report virtual memory statistics:

vmstat # basic memory statistics


vmstat 5 # update every 5 seconds
 iostat – Report CPU and I/O statistics:

iostat # basic CPU and I/O stats


iostat -x # extended statistics

 mpstat – Report CPU usage statistics:

mpstat # basic CPU usage statistics


mpstat -P ALL # CPU usage per core

 pidstat – Report statistics by process:

pidstat # general process stats


pidstat -u # show CPU usage per process
pidstat -d # show disk I/O stats per process

 free – Display memory usage:

free # general memory usage stats


free -h # human-readable format
free -m # in MB

 uptime – How long the system has been running:

uptime # show uptime

 watch – Execute a program periodically, showing output:

watch -n 1 free # watch memory usage every second


watch -d ls # watch directory contents and highlight
changes

 lshw – List hardware configuration:

lshw # list hardware configuration


lshw -short # concise summary of hardware
lshw -C network # show network devices only

 htop – Interactive process viewer (better than top):

htop # interactive process viewer


htop -u user # show processes of a specific user
htop -d 2 # set refresh interval to 2 seconds

 netstat – Network statistics (deprecated in favor of ss):

netstat # general network statistics


netstat -tuln # show listening ports and associated
processes
netstat -r # show routing table
 ss – Show socket statistics (more efficient than netstat):

ss # basic socket statistics


ss -tuln # show listening TCP/UDP ports
ss -p # show process using the socket

15. Networking & Remote Management

 ifconfig – Configure network interfaces (older command, replaced by ip):

ifconfig # show network interfaces


ifconfig eth0 up # bring eth0 interface up
ifconfig eth0 down # bring eth0 interface down
ifconfig -a # show all interfaces

 ip – A more modern alternative for managing network interfaces and routing:


o ip addr – Show IP addresses:

ip addr # show IP addresses


ip addr show eth0 # show IP for specific interface

o ip link – Show or manipulate network interfaces:

ip link # show interfaces


ip link set eth0 up # bring interface eth0 up
ip link set eth0 down # bring interface eth0 down

o ip route – Show or manipulate routing tables:

ip route # show routing table


ip route add [Link]/24 via [Link] # add a route

 ss – Display socket statistics (useful for diagnosing network issues):

ss # general socket stats


ss -tuln # show listening TCP/UDP ports

 nmap – Network exploration tool (can be used for security auditing):

nmap [Link] # scan a specific IP address


nmap -p 80 [Link] # scan port 80 of a specific IP
nmap -sP [Link]/24 # ping scan to discover live hosts

 telnet – User interface to the TELNET protocol (less common nowadays):

telnet [Link] # connect to a host using TELNET

 nc (Netcat) – Network utility for reading and writing from network connections:
o nc -l -p 1234 – Listen on port 1234:
nc -l -p 1234

o nc <host> <port> – Connect to a host and port:

nc [Link] 1234

 iptables – Administration tool for IPv4 packet filtering and NAT (Network Address
Translation):

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # allow SSH


sudo iptables -L # list current rules
sudo iptables -F # flush all rules

 firewalld – Frontend for managing firewall rules (used in some distros like Fedora and
CentOS):

sudo firewall-cmd --add-port=80/tcp --permanent # allow HTTP


sudo firewall-cmd --reload # apply changes

 ufw – Uncomplicated firewall (front-end for iptables):


o ufw enable – Enable firewall:

sudo ufw enable

o ufw allow <port> – Allow traffic on a specific port:

sudo ufw allow 80/tcp # allow HTTP

 tcpdump – Command-line packet analyzer:

sudo tcpdump -i eth0 # capture packets on eth0 interface


sudo tcpdump -i eth0 port 80 # capture HTTP traffic

 curl – Transfer data from or to a server using various protocols (HTTP, FTP, etc.):

curl [Link] # fetch data from a URL


curl -O [Link] # download a file
curl -I [Link] # fetch headers only

 wget – Download files from the web via HTTP, HTTPS, FTP:

wget [Link] # download a file


wget -c [Link] # continue a paused download

 scp – Secure copy over SSH (used to copy files between systems):
o scp [Link] user@remote:/path/to/destination/ – Copy file to remote server:

scp [Link] user@remote:/path/to/destination/


 rsync – Remote file and directory synchronization (often used for backups):
o rsync -avz /local/path/ remote:/remote/path/ – Sync directories:

rsync -avz /local/path/ remote:/remote/path/

16. Text Processing Utilities

 grep – Search for patterns within files:


o grep 'pattern' [Link] – Search for a pattern in a file:

grep 'pattern' [Link]

o grep -r 'pattern' /dir/ – Recursively search for a pattern:

grep -r 'pattern' /dir/

o grep -i 'pattern' [Link] – Case-insensitive search:

grep -i 'pattern' [Link]

o grep -v 'pattern' [Link] – Exclude lines matching the pattern:

grep -v 'pattern' [Link]

o grep -l 'pattern' [Link] – Show filenames containing the pattern:

grep -l 'pattern' [Link]

 sed – Stream editor for filtering and transforming text:


o sed 's/old/new/g' [Link] – Replace old with new globally:

sed 's/old/new/g' [Link]

o sed -i 's/old/new/g' [Link] – In-place edit (modify the file directly):

sed -i 's/old/new/g' [Link]

 awk – A powerful text processing language:


o awk '{print $1}' [Link] – Print the first column of each line in a file:

awk '{print $1}' [Link]

o awk -F':' '{print $1}' [Link] – Set a custom delimiter (e.g., colon):

awk -F':' '{print $1}' [Link]

 cut – Remove sections from each line of a file:


o cut -d ':' -f 1 /etc/passwd – Print the first field of each line, delimited by
":":

cut -d ':' -f 1 /etc/passwd

o cut -c 1-5 [Link] – Cut specific character positions from each line:

cut -c 1-5 [Link]

 sort – Sort lines of text files:


o sort [Link] – Sort file content in ascending order:

sort [Link]

o sort -r [Link] – Sort in reverse order:

sort -r [Link]

 uniq – Report or omit repeated lines in a file:


o sort [Link] | uniq – Sort and remove duplicate lines:

sort [Link] | uniq

o uniq -c [Link] – Count occurrences of each line:

uniq -c [Link]

 tee – Read from standard input and write to standard output and files:
o echo "text" | tee [Link] – Write to file and show output on screen:

echo "text" | tee [Link]

 tr – Translate or delete characters:


o echo "hello" | tr 'a-z' 'A-Z' – Convert lowercase to uppercase:

echo "hello" | tr 'a-z' 'A-Z'

o echo "hello" | tr -d 'a' – Delete character 'a' from the input:

echo "hello" | tr -d 'a'

 paste – Merge lines of files:


o paste [Link] [Link] – Combine lines of file1 and file2 side by side:

paste [Link] [Link]

 wc – Word, line, character, and byte count:


o wc -l [Link] – Count lines in a file:
wc -l [Link]

o wc -w [Link] – Count words in a file:

wc -w [Link]

17. System Shutdown and Reboot

 shutdown – Shut down the system:


o shutdown -h now – Immediately shut down:

sudo shutdown -h now

o shutdown -r now – Reboot the system:

sudo shutdown -r now

o shutdown -h +10 – Shut down after 10 minutes:

sudo shutdown -h +10

 reboot – Reboot the system:

sudo reboot

 halt – Halt the system immediately (equivalent to turning off power):

sudo halt

 poweroff – Power off the system:

sudo poweroff

 init – Change the runlevel (old-style system manager):


o init 0 – Shutdown:

sudo init 0

o init 6 – Reboot:

sudo init 6

18. File System Mounting and Management

 mount – Mount a file system:


o mount /dev/sda1 /mnt – Mount partition to a directory:
mount /dev/sda1 /mnt

o mount -t ext4 /dev/sda1 /mnt – Mount a partition with a specific file system
type:

mount -t ext4 /dev/sda1 /mnt

o mount -o loop [Link] /mnt – Mount an ISO file:

mount -o loop [Link] /mnt

 umount – Unmount a file system:


o umount /mnt – Unmount the file system mounted at /mnt:

umount /mnt

 fstab – File system table (configuration file for mounting file systems):
o /etc/fstab – View and configure persistent mount points:

cat /etc/fstab

 blkid – Display block device attributes:

blkid
blkid /dev/sda1 # get details about a specific device

 fsck – Check and repair a file system:


o fsck /dev/sda1 – Check and repair /dev/sda1:

sudo fsck /dev/sda1

o fsck -A – Check all file systems mentioned in /etc/fstab:

sudo fsck -A

19. Filesystem Permissions and Security

 chmod – Change file permissions:


o chmod 755 [Link] – Give read, write, and execute permissions to owner, and
read-execute permissions to others:
chmod 755 [Link]

o chmod u+x [Link] – Add execute permission to the owner:

chmod u+x [Link]

o chmod -R 755 directory/ – Apply permissions recursively to a directory:

chmod -R 755 directory/

 chown – Change file owner and group:


o chown user:group [Link] – Change owner and group of a file:

chown user:group [Link]

o chown -R user:group directory/ – Change owner and group recursively:

chown -R user:group directory/

 chgrp – Change group ownership of a file:


o chgrp group [Link] – Change the group of a file:

chgrp group [Link]

 umask – Set default permissions for new files:


o umask 022 – Set default permissions for newly created files to 755:

umask 022

 setfacl – Set access control lists (ACL) for file permissions:


o setfacl -m u:username:rwx [Link] – Give read, write, and execute
permissions to a specific user:

setfacl -m u:username:rwx [Link]

o setfacl -m g:groupname:rx [Link] – Give read and execute permissions to


a specific group:

setfacl -m g:groupname:rx [Link]


 getfacl – Get access control lists (ACL) for file permissions:
o getfacl [Link] – View ACL for a file:

getfacl [Link]

Common questions

Powered by AI

'awk' and 'cut' both extract data from text, but their functionalities differ. 'cut' is used for simple extraction of sections based on characters or fields. For instance, 'cut -d' ' -f1 file.txt' extracts the first field using a space delimiter. It's ideal for straightforward extraction tasks without complex criteria. 'awk', on the other hand, is much more versatile, offering full programming capabilities for text manipulation, such as '{print $1}' to show the first column or conditional field processing like 'awk -F, '{print $1}' file.txt'. 'awk' suits tasks that require more intricate logic, computations, or pattern-based data extraction, not just splitting based on delimiter positions .

The 'netstat' command is used to display network connections, routing tables, and interface statistics, aiding in network diagnostics. For example, 'netstat -tuln' shows all listening ports, which is helpful for identifying services running on a system. 'netstat -i' can display network interface statistics, beneficial for monitoring network errors. The routing table can be viewed using 'netstat -r', assisting in troubleshooting connectivity issues by validating that traffic is routed correctly .

The 'grep' command searches text using patterns and can be utilized to filter text in files. It supports case-insensitive searches using '-i', as in 'grep -i "pattern" file.txt', and can perform recursive directory searches with '-r', e.g., 'grep -r "pattern" /path/to/dir'. To exclude matching lines, use '-v', for instance, 'grep -v "pattern" file.txt'. Additionally, 'grep -l "pattern" *.txt' lists filenames containing the pattern, simplifying identification of relevant files .

'ps', 'top', and 'htop' each serve different roles in process monitoring. 'ps' provides a static snapshot of current processes, useful for scripting, detailed analysis, or when precise information at a specific moment is required. It offers options like 'ps -aux' for a user-oriented format. 'top' provides a real-time, dynamic view of processes, updating periodically to show CPU and memory usage, ideal for a quick system health check. 'htop' is an enhanced, interactive version of 'top' with a more user-friendly interface, offering features like process sorting, easy operations on them, and a customizable display. While 'ps' is suited for precise queries, 'top' and 'htop' are better for monitoring ongoing performance and resource usage .

'sed' and 'awk' are both text processing tools, but they have distinct purposes. 'sed' is a stream editor that performs basic text transformations on an input stream (a file or input from a pipeline). It is ideal for simple text replacement tasks, such as 'sed 's/old/new/g' file.txt' to replace 'old' with 'new'. Conversely, 'awk' is a full-fledged language designed for pattern scanning and processing. It excels in computational tasks and complex data extraction, such as '{print $1}' to print the first column in a file. Use 'sed' for straightforward find-and-replace operations and 'awk' for more complex data manipulations that involve conditionals and aggregations .

'locate' is used for quickly finding files by name, as it searches a prebuilt database of file paths. It is case-insensitive if used with '-i', making it faster than 'find', which performs a real-time directory traversal. 'locate' is preferable when up-to-date database usage suffices for a search, significantly speeding up the process since it doesn't directly access the file system. However, 'find' is necessary for more comprehensive searches involving complex logic like file size, modification date, or permissions, as in 'find /path/to/directory -name filename' .

The 'chmod' command in Linux is used to change file permissions, which control the actions that users can perform on a file or directory. For example, 'chmod 755 file1.sh' sets permissions so that the owner can read, write, and execute the file, while others can only read and execute it. Another example, 'chmod +x script.sh', adds execute permission, allowing a script to be run. Using 'chmod -R 755 directory', you can apply these changes recursively to a directory and its contents .

The 'chown' command changes the ownership of files and directories in Linux. It is used when ownership of a file needs to change to another user or group for access control. For example, 'chown user:group file1.txt' changes the owner to 'user' and the group to 'group'. When applying changes recursively to directories, 'chown -R user:group directory' modifies ownership for all contents within the directory, ensuring consistent access rights .

The 'mount' and 'umount' commands are complementary. 'mount' attaches a filesystem, such as a partition or an ISO, to a directory structure, enabling access to its contents. For example, 'mount /dev/sda1 /mnt' makes the contents of '/dev/sda1' accessible at '/mnt'. Conversely, 'umount' detaches it, making the content inaccessible, as in 'umount /mnt', which is critical before removing a physical device to prevent data loss. Use 'mount' to make filesystems available for use and 'umount' to safely remove access to them .

'df' and 'du' are both disk usage reporting commands in Linux, but they serve different purposes. 'df' reports the amount of disk space used and free on file systems, often by using 'df -h' for a human-readable format. For instance, 'df /path/to/directory' shows the disk space of the specified directory. In contrast, 'du' provides an estimate of file space usage on a more granular level, reporting sizes per file or directory, such as 'du -sh /path' for a summarized, human-readable output. While 'df' is better for an overview of the filesystem usage, 'du' is ideal for identifying large files or directories taking up space .

You might also like