DEV Community

Cover image for Linux Commands Cheat Sheet :)
Madhav Ganesan
Madhav Ganesan

Posted on Edited on

Linux Commands Cheat Sheet :)

Echo

The command is used to display a line of text or the value of variables on the terminal.

echo $name
echo Hello World
Enter fullscreen mode Exit fullscreen mode

Nano

  • It is a terminal-based text editor used to create and edit files.
  • It displays keyboard shortcuts at the bottom of the screen.
nano filename        # Open or create a file
# Ctrl + O, Enter     # Save the file
# Ctrl + X            # Exit nano
Enter fullscreen mode Exit fullscreen mode

VIM

  • It is a terminal-based text editor used to create and edit files.
  • It has different modes for editing text and running commands.
vi filename           # Open or create a file
# i                   # Enter insert mode to edit
# Esc                 # Return to command mode
# :w                  # Save the file
# :q                  # Quit
# :wq                 # Save and quit
# :q!                 # Quit without saving
Enter fullscreen mode Exit fullscreen mode

Print Env

The command is used to display all environment variables.

printenv
env
Enter fullscreen mode Exit fullscreen mode

History (history)

The command displays your shell’s command history.

history                 # display command history
history 10              # display the last 10 commands
history | grep "find"   # search history for commands containing find
Enter fullscreen mode Exit fullscreen mode

Tail

  • The command is used to display the last part of a file.
  • It updates in real time as they happen, without needing to reopen the file again.
tail -f filename // live logs
tail filename // last 10 lines
tail -n 50 filename // last 50 lines
Enter fullscreen mode Exit fullscreen mode

Listing Files (ls)

  • The command is used to list files and directories.
  • It has options that allows us to show hidden files, detailed information, and readable file sizes.
ls             # list files and directories
ls -a          # include hidden files
ls -l          # show detailed information
ls -lh         # show details with readable file sizes
ls -la         # show details, including hidden files
Enter fullscreen mode Exit fullscreen mode

Change Directory (cd)

  • The command is used to change the current working directory.
  • You can navigate using a directory name, a full path, or shortcuts.
cd Documents   # move into the Documents directory
cd /var/log    # move to /var/log
cd ..          # move up one directory
cd ~           # move to your home directory
cd             # move to your home directory
cd -           # return to the previous working directory
Enter fullscreen mode Exit fullscreen mode

cat

  • The command is used to display or combine file contents.
cat filename                  # display file contents
cat file1 file2               # display both files in order
cat -n filename               # display contents with line numbers
cat file1 file2 > combined    # combine files into a new file
cat > filename                # enter content; press Ctrl+D to finish
Enter fullscreen mode Exit fullscreen mode

Find (find)

find ~ -name "mission_brief.txt"    # search your home directory
find . -name "mission_brief.txt"    # search your current directory
find -name "passwords.txt"         # search your current directory (GNU find)
find . -iname "passwords.txt"      # search without case sensitivity
find . -type f -name "*.txt"       # find files ending in .txt
find . -type d -name "Documents"   # find directories named Documents
Enter fullscreen mode Exit fullscreen mode

whoami

The command displays the username associated with your current effective user ID.

Less

  • The command is used to view the contents of a file one screen at a time.
  • It allows scrolling forward and backward.
  • It allows searching for a particular text in the logs.
less filename
Enter fullscreen mode Exit fullscreen mode

Time and Date

The command is used to display or set the system date and time.

date // current date
timedatectl // detailed system date
Enter fullscreen mode Exit fullscreen mode

Grep

  • The command searches for matching text in files.
  • It displays lines containing the specified pattern and is case-sensitive by default.
grep "pass" passwords.txt       # display lines containing pass
grep -i "pass" passwords.txt    # search without case sensitivity
grep -n "pass" passwords.txt    # show matching lines with line numbers
grep -v "pass" passwords.txt    # display lines that do not contain pass
grep -r "pass" .                # search files recursively in the current directory
Enter fullscreen mode Exit fullscreen mode

Netcat

  • It is a command-line tool used to send and receive data over a network.
  • It can connect to a port on another computer or listen on a port for incoming connections.
nc <ip-address> <port>
# Connect to a TCP port

nc -v <ip-address> <port>
# Connect and show more details

nc -n <ip-address> <port>
# Connect without looking up hostnames

nc -zv <ip-address> <port>
# Check whether a TCP port accepts connections

nc -zv <ip-address> 20-100
# Check a range of TCP ports

nc -l -p <port>
# Listen for an incoming TCP connection

nc -lvnp <port>
# Listen with verbose output and no DNS lookup

nc -u <ip-address> <port>
# Send or receive UDP traffic
Enter fullscreen mode Exit fullscreen mode

Kill

It is used to stop all processes that match a given name

kill PID             # Send SIGTERM: ask the process to stop and clean up
kill -SIGKILL PID    # Force the process to stop immediately
kill -SIGSTOP PID    # Pause the process
kill -SIGCONT PID    # Resume a paused process
Enter fullscreen mode Exit fullscreen mode

Present Working Directory (pwd)

  • The command displays the full path of your current working directory.

Linux Manual Pages (man)

  • The command displays the manual page for a command.
  • It explains the command’s purpose, syntax, and available options.
man ls         # display the manual for ls
man grep       # display the manual for grep
man find       # display the manual for find
Enter fullscreen mode Exit fullscreen mode

ps

  • A process is any program that is currently running. Your browser, a terminal, and Apache can all run as processes.
  • Systemd is a specific program that runs as a process and helps manage other processes, especially background services.
  • It is used to display information about running processes.
  • It can show process IDs, CPU usage, memory usage, and the commands that started them.
  • Each process has a unique number called a process ID (PID).
ps                  # Show processes in the current terminal
ps -e               # Show all running processes
ps aux              # Show all processes with detailed information
ps -ef              # Show all processes in full format
(a - show all processes)
(u - display user)
(x - show processes not attached to the terminal)
Enter fullscreen mode Exit fullscreen mode

Namespace

It gives processes an isolated view of certain parts of the system.

Top

This command provides a real-time, interactive view of system processes, including CPU and memory usage.

top
Enter fullscreen mode Exit fullscreen mode

Systemctl

  • It is a command used to manage services on a Linux system that uses systemd.
  • It is a program that usually runs in the background. For example : Apache runs as a service to handle web requests.
sudo systemctl start apache2      # Start Apache now
sudo systemctl stop apache2       # Stop Apache now
sudo systemctl enable apache2     # Set Apache to start automatically on boot
sudo systemctl disable apache2    # Stop Apache from starting automatically on boot
systemctl status apache2          # Check whether Apache is running
Enter fullscreen mode Exit fullscreen mode

Secure Shell (ssh).

  • The command securely connects you to a remote computer.
  • You log in using a username and the remote computer’s IP address or hostname.
ssh username@ip         # connect as username using the default port 22
ssh -p 2222 username@ip # connect using port 2222
Enter fullscreen mode Exit fullscreen mode

ping

  • The command uses ICMP Echo Requests to test whether a device responds over the network.
  • It displays response times and packet loss. No reply does not always mean the device is offline; ICMP may be blocked.
ping ip_address       # send requests until stopped with Ctrl+C
ping -c 4 ip_address  # send 4 requests on Linux
ping -n 4 ip_address  # send 4 requests on Windows
Enter fullscreen mode Exit fullscreen mode

Telnet

  • It is a protocol used to connect to another computer over a network and interact with it through a command line.
  • It commonly uses TCP port 23.
  • It existed before SSH. It was designed for remote access when network security was less of a concern. SSH was introduced later to provide encrypted remote access.
telnet <ip-address> 80    # Connect to a Telnet server

GET / HTTP/1.1
Host: <ip-address>
Enter fullscreen mode Exit fullscreen mode

Deleting Files and Directories

rm <filename> //deletes a file
rm -f <filename> //deletes a file forcefully
rmdir <directory> //delete a directory
mkdir directory //create a folder
rm -rf <directory> //deletion of a directory and its content without confirmation
Enter fullscreen mode Exit fullscreen mode

Switch User (su)

  • The command switches to another user on the same machine.
  • It usually asks for the target user’s password.
  • Using - starts a login shell, loads the target user’s login environment, and changes to their home directory.
su - root      # switch to root with a login shell
su root        # switch to root, keeping the current directory
su - user      # switch to user with a login shell
su -           # switch to root with a login shell (root is the default)
exit           # return to the previous shell
Enter fullscreen mode Exit fullscreen mode

Ping utility

It is a basic tool used to test network connectivity. It helps to check if your computer can reach
another computer over the internet.

Round-trip time:
Time it takes for data to travel from source to the destination and back

When you use the ping command, your computer sends a small data packet called an "ICMP echo request" to the target address. The target then sends back a response called an "ICMP echo reply."

ping [url]
Enter fullscreen mode Exit fullscreen mode

Third party ping applications:
fping

What is the Default Gateway?

It is the IP address of a router or network device that your computer uses to communicate with other devices outside your local network. In other words, it's the address that your computer sends traffic to when it needs to access resources beyond its own subnet.

This means that any network traffic that needs to go beyond your local subnet (e.g., to the internet) will be sent to 172.22.8.1, which is likely the IP address of your router or gateway device.

If your computer wants to access a website, it sends the request to the default gateway (172.22.8.1), which then forwards the request to the internet. The gateway also handles incoming traffic from the internet and directs it back to your computer.

File Transfer Protocol

1) Connect to FTP server
It is used to connect to the FTP server from a terminal or command prompt.

ftp [url]
Enter fullscreen mode Exit fullscreen mode

FTP Client

Ex. FileZilla

Network Mapper (nmap)

It is a network scanning tool used for discovering hosts and services on a computer network. It’s widely used for security auditing, network inventory, and identifying network issues.

nmap -sT target_ip //scan open TCP ports
nmap -sU target_ip //scan open UDP ports 
nmap -A target_ip //agressive scan
Enter fullscreen mode Exit fullscreen mode
// Report
Lists all open ports
PORT    STATE SERVICE
21/tcp  open  ftp
80/tcp  open  http
110/tcp open  pop3
135/tcp open  msrpc
143/tcp open  imap
443/tcp open  https
Enter fullscreen mode Exit fullscreen mode

ifconfig(Similar to ipconfig of windows)

This command gives you the details about network interface cards(NIC)

ifconfig
Enter fullscreen mode Exit fullscreen mode

Symbolic Link (Symlink)

A symbolic link (or symlink) is a type of file that serves as a reference to another file or directory. It's essentially a shortcut or alias that points to the target file or directory.

ln -s [TARGET] [LINK_NAME]
Enter fullscreen mode Exit fullscreen mode

Remove orca

sudo apt remove orca
Enter fullscreen mode Exit fullscreen mode

Package management

apt-get install package-name
apt-get remove package-name
apt-get purge package-name
apt-get update
apt-get upgrade //upgrades all installed packages to the latest versions
Enter fullscreen mode Exit fullscreen mode

Single Dash (-): Used for single-letter options. Example: -h for help.
Double Dash (--): Used for word options. Example: --help for detailed help.

Create a New File:

touch filename.txt
cat > filename 
Enter fullscreen mode Exit fullscreen mode

Type your content and
Press Ctrl + D to save and exit.

Curl

  • It is used to transfer data to or from a server using a URL.
  • It can retrieve web pages, download files, and send requests to APIs.
curl https://example.com                 # Display the response
curl -I https://example.com              # Display response headers
curl -O https://example.com/file.txt     # Download a file
curl -X POST https://example.com/api     # Send a POST request
Enter fullscreen mode Exit fullscreen mode

Backgrounding process

sleep 60
Ctrl + Z
bg
jobs
Enter fullscreen mode Exit fullscreen mode

Foregrounding process

sleep 60 &
fg
Enter fullscreen mode Exit fullscreen mode

Crontab

  • It is used to schedule commands to run automatically at specific times.
  • For example, you can schedule a backup to run every day at midnight.
crontab -e    # Create or edit your scheduled jobs
crontab -l    # List your scheduled jobs
crontab -r    # Remove all your scheduled jobs

minute hour day-of-month month day-of-week command
Enter fullscreen mode Exit fullscreen mode

All Combinations

* * * * * /home/user/backup.sh        # Every minute
*/5 * * * * /home/user/backup.sh      # Every 5 minutes
0 * * * * /home/user/backup.sh        # Every hour
0 */2 * * * /home/user/backup.sh      # Every 2 hours
0 0 * * * /home/user/backup.sh        # Every day at midnight
30 8 * * * /home/user/backup.sh       # Every day at 8:30 AM
0 9 * * 1-5 /home/user/backup.sh      # Monday to Friday at 9:00 AM
0 9 * * 1 /home/user/backup.sh        # Every Monday at 9:00 AM
0 0 1 * * /home/user/backup.sh        # First day of every month at midnight
0 0 1 1 * /home/user/backup.sh        # January 1 at midnight
Enter fullscreen mode Exit fullscreen mode

Granting Permissions

Each file and directory must be allocated a particular level of permission
for the different identities using it. The three levels of permission are
listed hereunder:
r - (Read permission) This grants permission only to open and view a file.
w - (Write permission) This allows users to view and edit a file.
x - (Execute permission) This will enable users to execute a file (This does
not guarantee viewing or editing it).

Changing Permissions
We can use the Linux command **chmod **to change the permissions.

rwxrwxrwx
rwx for the owner: 7 (rwx)
rwx for the group: 7 (rwx)
rwx for others: 7 (rwx)
Enter fullscreen mode Exit fullscreen mode

Read (r) = 4 (binary 100)
Write (w) = 2 (binary 010)
Execute (x) = 1 (binary 001)

Common Directories

/etc (etcetera)

  • It is one of the most important root directories on your system.
  • It is a commonplace location where system and program files are stored.

/var (variable data)

  • It stores data that services and applications write to or read often, like log files (kept in /var/log), and other data not tied to a specific user, such as databases.

/root

  • It is the home directory of the root user, Linux’s administrator.
  • It is different from /, which is the top-level directory of the entire filesystem.

/home

  • It contains the home directories of regular users.
cd /home          # enter the directory containing users' home directories
cd /home/user     # enter user's home directory
Enter fullscreen mode Exit fullscreen mode

/tmp (temporary)

  • It stores temporary files created by applications and users.
  • It is generally writable by all users, but users normally cannot delete files owned by others.
  • Files may be automatically removed, including during a reboot. Avoid storing important files here.

Stay Connected!
If you enjoyed this post, don’t forget to follow me on social media for more updates and insights:

Twitter: madhavganesan
Instagram: madhavganesan
LinkedIn: madhavganesan

Top comments (2)

Collapse
 
brennan_maxwell_9c674c15e profile image
Brennan Maxwell •

Awesome summary of Linux commands! One additional command that I found helpful was the 'df' command for viewing storage status. Thanks for sharing this cheat sheet. :)

Collapse
 
madgan95 profile image
Madhav Ganesan •

Sure will add that💯