If you’ve ever felt that Linux is just for developers or tech experts, we’re here to change that perception. Yes, Linux might seem a bit daunting at first, but once you dive into it, you’ll see why so many people fall in love with its flexibility and power.
In fact, we’ve dedicated a whole book to it – Linux Playbook For Hacker’s. This book aims to guide you through the maze of commands and functionalities, making you comfortable and proficient with Linux.
Linux commands give you exceptional control over your computer, and once you get the hang of them, switching back to Windows or any other operating system might seem less appealing.
Our Linux Cheatsheet includes everything from basic commands to advanced techniques. You’ll find sections on file and directory management, file permissions, text processing, system information, networking, and more. Plus, we’ve packed it with useful shortcuts to speed up your workflow.
So, whether you’re just starting or looking to sharpen your skills, this cheatsheet is designed to be your handy reference. Dive in and discover the power of Linux!
What is Linux?
Linux is another flavor of Unix, and in many areas has reached them in popularity, being deployed in everything from desktops, laptops, and mobile devices to server farms, supercomputer clusters, and everything else in between. As opposed to proprietary operating systems (OS) such as Windows and macOS, Linux is open-source, meaning that the source code is made available for everyone to view, change, and share. Being open sourced there is an enormous and diverse community that helps maintain and improve it over time.
In simplest terms, Linux is made up of the Linux kernel – the core of the operating system – which is responsible for maintaining hardware resources and enabling software to communicate with hardware. Distributions (distros) build on top of that kernel, providing a rich mix of additional software, user interfaces, and services that can be mixed and matched to create complete operating systems suitable for a variety of different tasks. Some popular Linux distributions include Ubuntu, Fedora, Debian, and CentOS.
Linux is known for its stability, security, and flexibility. It is the preferred operating system for servers, cloud computing, and embedded systems, largely due to its robustness and the control it offers administrators. For developers and tech enthusiasts, Linux provides a rich environment for programming, scripting, and system administration.
Despite its reputation for being complex, Linux has become increasingly user-friendly, with many distributions offering intuitive graphical interfaces and extensive documentation.
#1. Basic Linux commands
Linux commands can seem intimidating at first glance, with their terse syntax and vast range of options. But fear not! Once you get the hang of them, you’ll realize that these commands are not only powerful but also incredibly efficient. Imagine being able to perform complex tasks with just a few keystrokes, automate repetitive actions, and troubleshoot issues with precision—all of this is possible with the right set of commands.
In this section, we’ll introduce you to some of the most fundamental Linux commands that you’ll need for day-to-day operations. From navigating the filesystem and managing files to checking system resources and configuring networks, these commands are your toolkit for mastering Linux. Each command is accompanied by a description, common options, and examples to help you understand how to use them effectively.
Our goal is to make you comfortable with the command line, demystifying its use and showing you how it can streamline your work. Whether you’re editing a file, changing permissions, or monitoring system performance, these commands will empower you to get things done efficiently and effectively.
So, let’s dive in and start exploring the basic Linux commands that will serve as your foundation in this powerful operating system. Below is a comprehensive table that lists these commands, along with their descriptions, options, and examples to help you get started.
Command | Description | Options | Example |
---|---|---|---|
pwd | Prints the current working directory | N/A | pwd |
ls | Lists directory contents | -l (long format), -a (all files), -h (human-readable) | ls -lh |
cd | Changes the directory | N/A | cd /home/user |
touch | Creates an empty file | N/A | touch file.txt |
cp | Copies files or directories | -r (recursive), -i (interactive) | cp file.txt /backup/ |
mv | Moves or renames files or directories | -i (interactive) | mv file.txt newfile.txt |
rm | Removes files or directories | -r (recursive), -f (force) | rm -rf folder |
cat | Concatenates and displays files | N/A | cat file.txt |
mkdir | Creates a new directory | -p (parent directories as needed) | mkdir new_folder |
rmdir | Removes empty directories | N/A | rmdir empty_folder |
chmod | Changes file permissions | Numeric (e.g., 755 ), Symbolic (e.g., u+x ) | chmod 755 script.sh |
chown | Changes file owner and group | user:group | chown user:group file.txt |
nano | Edits text files in the terminal | N/A | nano file.txt |
vi | Edits text files in the terminal | N/A | vi file.txt |
grep | Searches text using patterns | -i (ignore case), -r (recursive), -v (invert match) | grep -i 'search' file.txt |
df | Displays disk space usage | -h (human-readable) | df -h |
du | Displays file and directory space usage | -h (human-readable), -s (summary) | du -sh folder |
free | Displays memory usage | -h (human-readable) | free -h |
ps | Displays current processes | -e (all processes), -f (full format) | ps -ef |
top | Displays running processes | N/A | top |
kill | Terminates processes | N/A | kill 1234 (PID) |
ifconfig | Configures network interfaces | N/A | ifconfig eth0 |
ping | Checks network connectivity | N/A | ping google.com |
wget | Downloads files from the web | -c (continue), -P (directory) | wget -P /downloads URL |
ssh | Connects to remote machines securely | -i (identity file), -p (port) | ssh user@hostname |
scp | Securely copies files between hosts | -P (port) | scp file.txt user@host:/path |
#2. File Permission Commands
Managing file permissions is a crucial aspect of maintaining a secure and efficient Linux system. File permissions control who can read, write, or execute a file, and understanding how to set and modify these permissions is essential for any Linux user. Here’s an introduction to the most commonly used file permission commands, along with a comprehensive table that details their usage.
Understanding File Permissions
In Linux, each file and directory has a set of permissions for three different user categories:
- Owner: The user who owns the file.
- Group: The group that owns the file.
- Others: All other users.
Permissions are divided into three types:
- Read (r): Permission to read the file.
- Write (w): Permission to modify the file.
- Execute (x): Permission to execute the file as a program.
Each file’s permissions are displayed as a series of ten characters, for example: -rwxr-xr--
- The first character indicates the file type (e.g.,
-
for regular file,d
for directory). - The next three characters show the owner’s permissions.
- The following three characters show the group’s permissions.
- The last three characters show others’ permissions.
File Permission Commands Table
Command | Description | Options | Example |
---|---|---|---|
chmod | Changes file permissions | -R (recursive), Numeric (e.g., 755 ), Symbolic (e.g., u+x ) | chmod 755 script.sh |
chown | Changes file owner | -R (recursive) | chown user file.txt |
chgrp | Changes file group | -R (recursive) | chgrp group file.txt |
umask | Sets default file creation permissions | N/A | umask 022 |
stat | Displays detailed information about a file | N/A | stat file.txt |
Examples and Usage
chmod
(Change Mode)
The chmod
command changes the permissions of a file or directory. You can use either symbolic or numeric mode to specify permissions.
- Symbolic Mode:
u
(user/owner)g
(group)o
(others)a
(all)
chmod u+x script.sh # Adds execute permission for the owner
chmod g-w file.txt # Removes write permission for the group
chmod a+r file.txt # Adds read permission for everyone
- Numeric Mode:
r = 4
w = 2
x = 1
Combine these values to set permissions:
chmod 755 script.sh # Sets permissions to rwxr-xr-x
chmod 644 file.txt # Sets permissions to rw-r--r--
chown
(Change Owner)
The chown
command changes the ownership of a file or directory.
chown newuser file.txt # Changes the owner to 'newuser'
chown newuser:newgroup file.txt # Changes the owner to 'newuser' and group to 'newgroup'
chown -R newuser /path/to/dir # Recursively changes the owner of all files in the directory
chgrp
(Change Group)
The chgrp
command changes the group ownership of a file or directory.
chgrp newgroup file.txt # Changes the group to 'newgroup'
chgrp -R newgroup /path/to/dir # Recursively changes the group of all files in the directory
umask
(User File Creation Mask)
The umask
command sets the default permissions for newly created files and directories.
umask 022 # Sets default permissions to 755 for directories and 644 for files
stat
(File Status)
The stat
command provides detailed information about a file, including its permissions, owner, size, and modification time.
stat file.txt
#3. Environment Variables Commands
Environment variables are a basic aspect of the Linux foundation and they are used broadly to influence the conduct of software in the process imposing changes where needed. They are used for storing information such as the user preferences, system settings, and the locations of executable files. A Linux user must learn how to handle these variables. This section provides an overview of the commands most often used to interact with environment variables with a handy table listing the commands that provide a high-level, cheat-sheet-like view of their use.
Environment variables are dynamic values that can affect the way running processes behave on a computer. They can be system-wide or user-specific. Common environment variables include:
PATH
: Specifies the directories where executable files are located.HOME
: The current user’s home directory.USER
: The name of the current user.SHELL
: The path to the current user’s shell.
Environment Variables Commands Table
Command | Description | Options | Example |
---|---|---|---|
printenv | Prints all or specific environment variables | N/A | printenv |
env | Runs a command in a modified environment | N/A | env |
set | Lists or sets shell variables | N/A | set |
export | Sets environment variables | N/A | export PATH=/usr/local/bin:$PATH |
unset | Unsets environment variables | N/A | unset VARIABLE_NAME |
echo | Displays the value of an environment variable | N/A | echo $HOME |
Examples and Usage
printenv
(Print Environment)
The printenv
command prints all or the specified environment variables.
printenv # Prints all environment variables
printenv PATH # Prints the value of the PATH variable
env
(Environment)
The env
command runs a command with a modified environment. It can also be used to print all environment variables.
env # Prints all environment variables
env VAR=value command # Runs 'command' with VAR set to 'value'
set
(Set Shell Variables)
The set
command lists or sets shell variables.
set # Lists all shell variables and functions
export
(Export Environment Variables)
The export
command sets environment variables so they are available to child processes.
export PATH=/usr/local/bin:$PATH # Adds /usr/local/bin to the PATH
export EDITOR=nano # Sets the default editor to nano
unset
(Unset Environment Variables)
The unset
command removes environment variables.
unset PATH # Unsets the PATH variable
unset EDITOR # Unsets the EDITOR variable
echo
(Echo Value)
The echo
command displays the value of an environment variable.
echo $HOME # Prints the home directory
echo $USER # Prints the current user name
#4. User Management Commands in Linux
For all Linux system administrators, managing users is a basic task. With these commands, you can create, edit and delete user accounts, and manage user group permissions. Here is the list of an introduction to of several the most used user management commands and details in the tables below.
Every user has a unique user ID (UID) and is a member of one or more groups, each with a unique group ID (GID). It includes tasks like adding new users, editing current users, managing group memberships, and implementing some basic security for user accounts.
User Management Commands Table
Command | Description | Options | Example |
---|---|---|---|
useradd | Adds a new user | -m (create a home directory), -G (additional groups), -s (shell) | useradd -m -s /bin/bash newuser |
usermod | Modifies an existing user | -aG (add to group), -s (shell), -d (home directory) | usermod -aG sudo newuser |
userdel | Deletes a user | -r (remove home directory) | userdel -r newuser |
groupadd | Adds a new group | N/A | groupadd newgroup |
groupmod | Modifies an existing group | -n (new name) | groupmod -n newname oldgroup |
groupdel | Deletes a group | N/A | groupdel newgroup |
passwd | Changes user password | N/A | passwd newuser |
chage | Changes user password expiry information | -l (list), -E (expiry date), -m (minimum days) | chage -E 2024-12-31 newuser |
id | Displays user ID and group ID | -u (user ID), -g (group ID), -G (all groups) | id newuser |
su | Switches to another user | - (login shell) | su - newuser |
sudo | Executes a command as another user | -u (user) | sudo -u newuser command |
Examples and Usage
useradd
(Add User)
The useradd
the command creates a new user.
useradd -m -s /bin/bash newuser # Adds a new user with a home directory and bash shell
useradd -m -G sudo newuser # Adds a new user and adds them to the sudo group
usermod
(Modify User)
The usermod
command modifies an existing user account.
usermod -aG sudo newuser # Adds the user to the sudo group
usermod -s /bin/zsh newuser # Changes the user's shell to zsh
usermod -d /new/home newuser # Changes the user's home directory
userdel
(Delete User)
The userdel
command removes a user account.
userdel newuser # Deletes the user
userdel -r newuser # Deletes the user and their home directory
groupadd
(Add Group)
The groupadd
command creates a new group.
groupadd newgroup # Creates a new group
groupmod
(Modify Group)
The groupmod
command modifies an existing group.
groupmod -n newname oldgroup # Renames the group
groupdel
(Delete Group)
The groupdel
command removes a group.
groupdel newgroup # Deletes the group
passwd
(Change Password)
The passwd
command changes the password of a user.
passwd newuser # Changes the password of the user
chage
(Change Age)
The chage
command changes password expiration information for a user.
chage -l newuser # Lists password expiry information for the user
chage -E 2024-12-31 newuser # Sets the account expiry date
chage -m 7 newuser # Sets the minimum number of days between password changes
id
(User ID)
The id
command displays the user ID (UID) and group ID (GID) of a user.
id newuser # Displays UID, GID, and group memberships
id -u newuser # Displays only the UID
id -g newuser # Displays only the GID
id -G newuser # Displays all group IDs
su
(Substitute User)
The su
command switches to another user.
su - newuser # Switches to the newuser account with a login shell
sudo
(Super User Do)
The sudo
command allows a permitted user to execute a command as the superuser or another user.
sudo -u newuser command # Executes the command as newuser
sudo apt-get update # Runs the update command with superuser privileges
#5. Networking Commands in Linux
Networking is an important part of the Linux system administration, it allows for connecting other systems, file transfer, troubleshooting network issues, etc. Basic understanding and use of the networking commands line will help you to administrate the network configurations and troubleshoot more efficiently. The following is an introduction to the most frequently used networking commands with a comprehensive chart including the commands.
Linux networking commands configure network interfaces, check connectivity, manage network services, and analyze network parameters. General networking commands are used to configure and manage network connections for the proper working of devices that can communicate over a computer network using chips, cards, cables, and other resources.
Networking Commands Table
Command | Description | Options | Example |
---|---|---|---|
ifconfig | Configures network interfaces | up (activate), down (deactivate), inet (IP address) | ifconfig eth0 up |
ip | Shows/manages IP addresses and routes | addr (address), link (device), route (routing table) | ip addr show |
ping | Checks network connectivity | -c (count), -i (interval), -t (TTL) | ping -c 4 google.com |
traceroute | Traces the route packets take to a network host | -n (numeric), -m (max hops) | traceroute google.com |
netstat | Displays network connections and statistics | -a (all), -t (TCP), -u (UDP), -p (program) | netstat -tuln |
ss | Displays socket statistics | -l (listening), -t (TCP), -u (UDP), -p (process) | ss -tuln |
dig | Queries DNS information | @server (DNS server), +short (short output) | dig google.com |
nslookup | Queries DNS to obtain domain name or IP address mapping | N/A | nslookup google.com |
scp | Securely copies files between hosts | -P (port), -r (recursive) | scp file.txt user@host:/path |
ssh | Connects to remote machines securely | -i (identity file), -p (port) | ssh user@hostname |
ftp | Transfers files to/from a remote host | -i (interactive mode), -n (no auto-login) | ftp hostname |
wget | Downloads files from the web | -c (continue), -P (directory) | wget -P /downloads URL |
curl | Transfers data from or to a server | -O (remote-name), -L (location) | curl -O http://example.com/file.txt |
route | Displays/manages the IP routing table | -n (numeric), add (add route), del (delete route) | route -n |
hostname | Shows or sets the system’s hostname | -i (IP address), -f (full) | hostname -i |
Examples and Usage
ifconfig
(Interface Configuration)
The ifconfig
command is used to configure network interfaces.
ifconfig # Displays all active interfaces
ifconfig eth0 up # Activates the eth0 interface
ifconfig eth0 down # Deactivates the eth0 interface
ifconfig eth0 192.168.1.100 # Assigns IP address to eth0
ip
(IP Address Management)
The ip
command is a powerful tool for managing IP addresses and routing.
ip addr show # Displays all IP addresses
ip link set eth0 up # Activates the eth0 interface
ip addr add 192.168.1.100/24 dev eth0 # Assigns IP address to eth0
ip route show # Displays the routing table
ping
(Packet Internet Groper)
The ping
command tests connectivity to another network host.
ping google.com # Pings google.com continuously
ping -c 4 google.com # Pings google.com 4 times
ping -i 0.5 google.com # Pings google.com with a 0.5-second interval
traceroute
(Trace Route)
The traceroute
command shows the route packets take to reach a host.
traceroute google.com # Traces the route to google.com
traceroute -n google.com # Traces the route numerically
traceroute -m 10 google.com # Limits the trace to 10 hops
netstat
(Network Statistics)
The netstat
command displays network connections, routing tables, and more.
netstat -a # Shows all connections
netstat -tuln # Shows listening TCP and UDP ports
netstat -p # Shows connections and the PID/program name
ss
(Socket Statistics)
The ss
command provides detailed socket information.
ss -tuln # Lists listening TCP and UDP ports
ss -tp # Shows TCP sockets with process information
dig
(Domain Information Groper)
The dig
command queries DNS servers for information.
dig google.com # Queries DNS information for google.com
dig @8.8.8.8 google.com # Uses a specific DNS server (8.8.8.8)
dig google.com +short # Provides a short, concise answer
nslookup
(Name Server Lookup)
The nslookup
command queries DNS to obtain domain name or IP address mapping.
nslookup google.com # Queries DNS for google.com information
nslookup 8.8.8.8 # Queries the IP address for its domain name
scp
(Secure Copy)
The scp
command securely copies files between hosts.
scp file.txt user@remote:/path # Copies file.txt to a remote server
scp -r local_dir user@remote:/path # Recursively copies a directory to a remote server
ssh
(Secure Shell)
The ssh
command connects to remote machines securely.
ssh user@hostname # Connects to a remote host
ssh -p 2222 user@hostname # Connects to a remote host on a specific port
ssh -i /path/to/key user@hostname # Connects using a specific identity file
ftp
(File Transfer Protocol)
The ftp
command transfers files to/from a remote host.
ftp hostname # Connects to an FTP server
ftp -n hostname # Connects without auto-login
wget
(Web Get)
The wget
command downloads files from the web.
wget http://example.com/file.txt # Downloads a file from the web
wget -c http://example.com/file.txt # Continues an interrupted download
wget -P /downloads http://example.com/file.txt # Downloads to a specific directory
curl
(Client URL)
The curl
command transfers data from or to a server.
curl -O http://example.com/file.txt # Downloads a file from the web
curl -L http://example.com # Follows redirects
route
(Routing Table)
The route
command displays or modifies the IP routing table.
route -n # Displays the routing table numerically
route add default gw 192.168.1.1 # Adds a default gateway
route del default gw 192.168.1.1 # Deletes a default gateway
hostname
(Show or Set Hostname)
The hostname
the command shows or sets the system’s hostname.
hostname # Displays the current hostname
hostname newhostname # Sets a new hostname
hostname -i # Displays the IP address of the hostname
#6. Process Management Commands in Linux
One of the major tasks of a Linux system administrator is process management. Processes are essentially running programs, and knowing how to work with them gives you a way to check system utilization, stop stuck processes, and ensure your computer is using its resources efficiently. Introduction to Common Process Management CommandsA list of how and when to use each process management command can be useful to bookmark for later when you find yourself needing to check on at what state one or more of these commands are running.
Linux Process can be system processes or user Processes which can be foreground too or Background process. Commands to visit your processes, process management commands that is. The fundamental concepts reviewing the process IDs (PIDs), parent-child process relationships, and the signal to control the process.
Process Management Commands Table
Command | Description | Options | Example |
---|---|---|---|
ps | Displays current processes | -e (all processes), -f (full format), -u (user) | ps -ef |
top | Displays and updates process information | -d (delay), -n (number of iterations) | top |
htop | Interactive process viewer | N/A | htop |
kill | Sends a signal to a process | -9 (force kill) | kill 1234 |
killall | Sends a signal to multiple processes by name | -9 (force kill) | killall firefox |
pkill | Sends a signal to processes by name or attribute | -9 (force kill), -u (user) | pkill -9 chrome |
nice | Starts a process with a given priority | -n (priority) | nice -n 10 command |
renice | Changes the priority of an existing process | -n (priority), -p (process) | renice -n 15 -p 1234 |
bg | Resumes a suspended job in the background | N/A | bg %1 |
fg | Brings a background job to the foreground | N/A | fg %1 |
jobs | Lists current jobs | -l (list with PIDs) | jobs -l |
nohup | Runs a command immune to hangups | N/A | nohup command & |
at | Schedules a command to run at a later time | -f (file), -m (mail) | at 10:00 AM tomorrow |
cron | Schedules recurring tasks | N/A | crontab -e |
service | Manages system services | start , stop , restart , status | service apache2 restart |
systemctl | Controls the systemd system and service manager | start , stop , restart , status | systemctl restart apache2 |
Examples and Usage
ps
(Process Status)
The ps
command displays information about active processes.
ps -ef # Displays all processes in full format
ps aux # Displays processes with detailed user-oriented output
ps -u username # Displays processes for a specific user
top
(Table of Processes)
The top
command provides a dynamic, real-time view of running processes.
top # Displays active processes and updates every few seconds
top -d 5 # Updates the display every 5 seconds
top -n 10 # Displays 10 iterations and then exits
htop
(Interactive Process Viewer)
The htop
command is an interactive process viewer, similar to top
, but with a more user-friendly interface.
htop # Launches the interactive process viewer
kill
(Terminate a Process)
The kill
command sends a signal to a process, typically to terminate it.
kill 1234 # Terminates the process with PID 1234
kill -9 1234 # Forcefully terminates the process with PID 1234
killall
(Terminate Processes by Name)
The killall
command sends a signal to all processes running a specified command.
killall firefox # Terminates all instances of Firefox
killall -9 firefox # Forcefully terminates all instances of Firefox
pkill
(Terminate Processes by Attribute)
The pkill
command sends a signal to processes based on name or other attributes.
pkill chrome # Terminates all processes with the name "chrome"
pkill -9 chrome # Forcefully terminates all processes with the name "chrome"
pkill -u username # Terminates all processes owned by a specific user
nice
(Set Process Priority)
The nice
command starts a process with a specified priority.
nice -n 10 command # Starts the command with a nice value of 10
renice
(Change Process Priority)
The renice
command changes the priority of an existing process.
renice -n 15 -p 1234 # Changes the priority of the process with PID 1234 to 15
bg
(Background)
The bg
command resumes a suspended job in the background.
bg %1 # Resumes job number 1 in the background
fg
(Foreground)
The fg
command brings a background job to the foreground.
fg %1 # Brings job number 1 to the foreground
jobs
(List Jobs)
The jobs
command lists current jobs.
jobs -l # Lists jobs with their PIDs
nohup
(No Hang Up)
The nohup
command runs a command immune to hangups, with output to a file.
nohup command & # Runs command immune to hangups in the background
at
(Schedule a Command)
The at
command schedules a command to run at a later time.
at 10:00 AM tomorrow # Schedules a command to run at 10:00 AM tomorrow
echo "command" | at now + 1 hour # Schedules a command to run in one hour
cron
(Schedule Recurring Tasks)
The cron
command schedules recurring tasks.
crontab -e # Edits the current user's crontab file
service
(Manage System Services)
The service
command manages system services.
service apache2 restart # Restarts the Apache2 service
service apache2 status # Checks the status of the Apache2 service
systemctl
(Control System and Service Manager)
The systemctl
command controls the systemd system and service manager.
systemctl start apache2 # Starts the Apache2 service
systemctl stop apache2 # Stops the Apache2 service
systemctl restart apache2 # Restarts the Apache2 service
systemctl status apache2 # Checks the status of the Apache2 service
#7. File Compression and Archiving Commands in Linux
Compression and archiving files is an important task when it comes to handling disk space, putting some order in the files, and transferring the data to a destination with sense. There are many tools available for use in Linux for compressing, decompressing, and archiving files. Original (Link)Introduction to Frequently Used Commands of File Compression & File Archiving with a Detailed Table
Compression Squashes Files So They Transfer Easier An archiving collects multiple files into one file before compressing it. Common tools include gzip, bzip2, xz for compression, and tar for archiving.
File Compression and Archiving Commands Table
Command | Description | Options | Example |
---|---|---|---|
tar | Archives multiple files into a single file | -c (create), -x (extract), -v (verbose), -f (file), -z (gzip), -j (bzip2), -J (xz) | tar -czvf archive.tar.gz /path/to/dir |
gzip | Compresses files | -d (decompress), -k (keep original) | gzip file.txt |
gunzip | Decompresses .gz files | N/A | gunzip file.txt.gz |
bzip2 | Compresses files using bzip2 | -d (decompress), -k (keep original) | bzip2 file.txt |
bunzip2 | Decompresses .bz2 files | N/A | bunzip2 file.txt.bz2 |
xz | Compresses files using xz | -d (decompress), -k (keep original) | xz file.txt |
unxz | Decompresses .xz files | N/A | unxz file.txt.xz |
zip | Creates ZIP archives | -r (recursive), -d (delete) | zip archive.zip file1 file2 |
unzip | Extracts ZIP archives | -l (list), -d (extract to directory) | unzip archive.zip |
rar | Creates RAR archives | -a (add), -x (extract), -v (verbose) | rar a archive.rar file1 file2 |
unrar | Extracts RAR archives | -l (list), -e (extract) | unrar e archive.rar |
Examples and Usage
tar
(Tape Archive)
The tar
command is used to create and manipulate archive files.
tar -czvf archive.tar.gz /path/to/dir # Creates a gzip-compressed archive of a directory
tar -xzvf archive.tar.gz # Extracts a gzip-compressed archive
tar -cjvf archive.tar.bz2 /path/to/dir # Creates a bzip2-compressed archive of a directory
tar -xjvf archive.tar.bz2 # Extracts a bzip2-compressed archive
tar -cJvf archive.tar.xz /path/to/dir # Creates an xz-compressed archive of a directory
tar -xJvf archive.tar.xz # Extracts an xz-compressed archive
gzip
(GNU Zip)
The gzip
command compresses files.
gzip file.txt # Compresses file.txt, resulting in file.txt.gz
gzip -d file.txt.gz # Decompresses file.txt.gz, resulting in file.txt
gzip -k file.txt # Compresses file.txt and keeps the original file
gunzip
(GNU Unzip)
The gunzip
command decompresses .gz
files.
gunzip file.txt.gz # Decompresses file.txt.gz, resulting in file.txt
bzip2
(Bzip2 Compression)
The bzip2
command compresses files using the bzip2 algorithm.
bzip2 file.txt # Compresses file.txt, resulting in file.txt.bz2
bzip2 -d file.txt.bz2 # Decompresses file.txt.bz2, resulting in file.txt
bzip2 -k file.txt # Compresses file.txt and keeps the original file
bunzip2
(Bzip2 Decompression)
The bunzip2
command decompresses .bz2
files.
bunzip2 file.txt.bz2 # Decompresses file.txt.bz2, resulting in file.txt
xz
(XZ Compression)
The xz
command compresses files using the xz algorithm.
xz file.txt # Compresses file.txt, resulting in file.txt.xz
xz -d file.txt.xz # Decompresses file.txt.xz, resulting in file.txt
xz -k file.txt # Compresses file.txt and keeps the original file
unxz
(XZ Decompression)
The unxz
command decompresses .xz
files.
unxz file.txt.xz # Decompresses file.txt.xz, resulting in file.txt
zip
(ZIP Archive)
The zip
command creates ZIP archives.
zip archive.zip file1 file2 # Creates a ZIP archive containing file1 and file2
zip -r archive.zip /path/to/dir # Recursively adds a directory to a ZIP archive
zip -d archive.zip file1 # Deletes file1 from the ZIP archive
unzip
(Unzip Archive)
The unzip
command extracts ZIP archives.
unzip archive.zip # Extracts the contents of the ZIP archive
unzip -l archive.zip # Lists the contents of the ZIP archive
unzip archive.zip -d /path/to/dir # Extracts the contents to a specific directory
rar
(RAR Archive)
The rar
command creates RAR archives.
rar a archive.rar file1 file2 # Creates a RAR archive containing file1 and file2
rar x archive.rar # Extracts the contents of the RAR archive
rar l archive.rar # Lists the contents of the RAR archive
unrar
(Unrar Archive)
The unrar
command extracts RAR archives.
unrar e archive.rar # Extracts the contents of the RAR archive
unrar l archive.rar # Lists the contents of the RAR archive
#8. IO Redirection Commands in Linux
A feature of Linux, which we will be looking at in this article, is IO (Input/Output) redirection. For example for the redirection of the output of commands to files or the chaining of commands together or the conditional handling of errors, etc. In this tutorial, we present an introduction to the most used IO redirection commands: a comprehensive table where we describe their usage formally.
In Linux, every process is associated with three standard IO streams:
- Standard Input (stdin): The default source of input (usually the keyboard). File descriptor is 0.
- Standard Output (stdout): The default destination of output (usually the terminal). File descriptor is 1.
- Standard Error (stderr): The default destination for error messages (usually the terminal). File descriptor is 2.
Redirection allows you to change the default source or destination of these streams.
IO Redirection Commands Table
Command | Description | Syntax | Example |
---|---|---|---|
> | Redirects stdout to a file (overwrite) | command > file | ls > output.txt |
>> | Redirects stdout to a file (append) | command >> file | ls >> output.txt |
< | Redirects stdin from a file | command < file | sort < input.txt |
2> | Redirects stderr to a file (overwrite) | command 2> file | ls nonexist > output.txt 2> error.txt |
2>> | Redirects stderr to a file (append) | command 2>> file | ls nonexist >> output.txt 2>> error.txt |
&> | Redirects both stdout and stderr to a file (overwrite) | command &> file | ls &> output.txt |
&>> | Redirects both stdout and stderr to a file (append) | command &>> file | ls &>> output.txt |
| | Pipes stdout of one command to stdin of another | command1 | command2 | ls | grep txt |
tee | Reads from stdin and writes to stdout and files | command | tee file | ls | tee output.txt |
<< | Here document for providing multi-line input | command << delimiter ... delimiter | cat << EOF ... EOF |
<& | Duplicates stdin | command <&n | read var <&0 |
>& | Duplicates stdout | command >&n | echo "message" >&2 |
Examples and Usage
Redirecting Standard Output
>
(Overwrite)
Redirects the standard output of a command to a file, overwriting the file if it exists.
ls > output.txt # Redirects the output of ls to output.txt, overwriting it
>>
(Append)
Redirects the standard output of a command to a file, appending to the file if it exists.
ls >> output.txt # Appends the output of ls to output.txt
Redirecting Standard Input
<
(Input Redirection)
Redirects the standard input of a command from a file.
sort < input.txt # Takes input for sort from input.txt
Redirecting Standard Error
2>
(Overwrite)
Redirects the standard error of a command to a file, overwriting the file if it exists.
ls nonexist 2> error.txt # Redirects error messages of ls to error.txt, overwriting it
2>>
(Append)
Redirects the standard error of a command to a file, appending to the file if it exists.
ls nonexist 2>> error.txt # Appends error messages of ls to error.txt
Redirecting Both Standard Output and Error
&>
(Overwrite)
Redirects both standard output and standard error to a file, overwriting the file if it exists.
ls &> output.txt # Redirects both output and errors of ls to output.txt, overwriting it
&>>
(Append)
Redirects both standard output and standard error to a file, appending to the file if it exists.
ls &>> output.txt # Appends both output and errors of ls to output.txt
Piping Commands
|
(Pipe)
Pipes the standard output of one command to the standard input of another.
ls | grep txt # Pipes the output of ls to grep to find lines containing 'txt'
tee
Command
The tee
command reads from standard input and writes to both standard output and files.
ls | tee output.txt # Writes the output of ls to both the terminal and output.txt
Here Document
<<
(Here Document)
Allows you to provide multi-line input to a command.
cat << EOF
This is a
multi-line input
EOF
Duplicating File Descriptors
<&
(Duplicate stdin)
Duplicates standard input from another file descriptor.
read var <&0 # Reads input from file descriptor 0 (stdin)
>&
(Duplicate stdout)
Duplicates standard output to another file descriptor.
echo "message" >&2 # Sends the message to file descriptor 2 (stderr)
#9. Shortcuts Commands in Linux
Many shortcut commands in Linux can help you be more productive. Here are a few of the most common ones:
9.1: Bash Shortcuts Commands
Bash, the Bourne Again Shell, provides numerous keyboard shortcuts to improve your efficiency while working in the terminal.
Shortcut | Description | Example |
---|---|---|
Ctrl + A | Move to the beginning of the line | |
Ctrl + E | Move to the end of the line | |
Ctrl + U | Cut (kill) the line before the cursor | |
Ctrl + K | Cut (kill) the line after the cursor | |
Ctrl + Y | Paste (yank) the cut text | |
Ctrl + W | Cut the word before the cursor | |
Ctrl + R | Search through command history | |
Ctrl + L | Clear the screen (same as clear command) | |
!! | Repeat the last command | !! |
!n | Repeat the nth command from history | !5 (repeats the 5th command) |
Ctrl + C | Interrupt/Kill the current process | |
Ctrl + D | Logout from the current session |
9.2: Nano Shortcuts Commands
Nano is a simple, user-friendly text editor. Here are some essential shortcuts for efficient editing.
Shortcut | Description |
---|---|
Ctrl + O | Write out (save) the file |
Ctrl + X | Exit nano |
Ctrl + K | Cut the current line |
Ctrl + U | Paste the cut text |
Ctrl + W | Search within the file |
Ctrl + J | Justify the current paragraph |
Ctrl + C | Show the current cursor position |
Ctrl + G | Display help |
Ctrl + \ | Replace text |
Alt + A | Start selecting text |
Alt + 6 | Copy the selected text |
9.3: VI Shortcuts Commands
VI is a powerful text editor that comes pre-installed on most Unix systems. Here are some common shortcuts for both command and insert modes.
Shortcut | Description |
---|---|
i | Switch to insert mode |
Esc | Switch to command mode |
:w | Save the file |
:q | Quit VI |
:wq | Save and quit VI |
:q! | Quit without saving |
dd | Delete the current line |
yy | Yank (copy) the current line |
p | Paste the yanked text |
/pattern | Search for a pattern |
u | Undo the last change |
Ctrl + R | Redo the last undone change |
gg | Go to the beginning of the file |
G | Go to the end of the file |
x | Delete the character under the cursor |
9.4: Vim Shortcuts Commands
Vim, an enhanced version of VI, provides additional shortcuts and functionalities. Here are some common Vim shortcuts for productivity.
Shortcut | Description |
---|---|
:w | Save the file |
:q | Quit Vim |
:wq | Save and quit Vim |
:q! | Quit without saving |
dd | Delete the current line |
yy | Yank (copy) the current line |
p | Paste the yanked text |
/pattern | Search for a pattern |
u | Undo the last change |
Ctrl + R | Redo the last undone change |
gg | Go to the beginning of the file |
G | Go to the end of the file |
x | Delete the character under the cursor |
:set nu | Show line numbers |
:set nonu | Hide line numbers |
v | Start visual mode (select text) |
Ctrl + V | Start visual block mode |
These shortcuts can significantly enhance your productivity by making navigation and editing in the terminal and text editors more efficient. Keep this cheatsheet handy as a quick reference while working on your Linux system.
Very informative